How to sort letters and numbers in JavaScript and Lodash?

1

Classify Lodash comes first number after letter, for example:

const myArray = ['2', '5', '10', 'A', '1']; //sim, número String
const result = _.orderBy(myArray, item => parseInt(item), 'asc');
//['1', '2', '5', '10', 'A']; 

I would like an output like this ['A', '1', '2', '5', '10'] . I tried another way, but it did not work out as a result I wanted:

const result = _.orderBy(myArray, (a,b) => b - a, 'asc');
    
asked by anonymous 17.05.2017 / 20:49

2 answers

0

As far as I know, lodash does sort for keys, but not for content.

To separate numbers and letters I suggest starting from two arrays, organizing each one and then putting them together.

It could be something like this:

function sortAlphaNum(arr) {
  const letters = [];
  const numbers = [];
  for (let i = 0, l = arr.length; i < l; i++) {
    if (arr[i].match(/\d+/)) numbers.push(arr[i]);
    else letters.push(arr[i]);
  }
  return letters.sort().concat(numbers.sort((a, b) => a - b));

}

const myArray = ['2', '5', 'C', '10', 'A', '1'];
console.log(sortAlphaNum(myArray));
    
17.05.2017 / 22:58
0

I do not know if it is possible with common methods of ordering, because of the natural ordering of the elements.

If you do a test, such as:

var lista = ['1', '4', 'C', '6', '2', 'A'];

function OrdenarArray(a, b) {
        return a > b;
    }

will have a result: ['1', '2', '4', '6', 'A', ...]

I ordered with a certain effort:

var lista = ['10', '4', 'C', '6', '2', 'A'];

function OrdenarArray(a, b) {
    return a > b;
}

var lLetras = new Array();
var lNumeros = new Array();
$.each(lista, function(indice, obj) {
    if (!isNaN(parseInt(obj, 0)))
       lNumeros.push(Number(obj));
    else
       lLetras.push(obj);
});

lLetras = lLetras.sort(OrdenarArray);
lNumeros = lNumeros.sort(OrdenarArray);

lista = lLetras;
$.each(lNumeros, function(indice, obj) {
    lista.push(obj.toString());
});

Final result: ['A', 'C', '2', '4', ...]

Of course there must be better ways to order. Oh, and I used jquery. = x

    
17.05.2017 / 23:01