How to classify letters and numbers in Javascript and Lodash?

Asked

Viewed 174 times

1

Sort pattern of 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 wish I had a way out like this ['A', '1', '2', '5', '10']. I tried another way, but it didn’t come out as a result I wanted to:

const result = _.orderBy(myArray, (a,b) => b - a, 'asc');

2 answers

0


That I know of lodash ago sort by keys, but not by content.

To separate numbers and letters I suggest starting in two array, organizing each one and then joining them.

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));

0

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

If you take a test, how:

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 sort. Ah, and I used jquery. = x

  • Using 10 does not work: https://jsfiddle.net/Lkpscrf8/1/

  • Ready, @Sergio. https://jsfiddle.net/Lkpscrf8/5/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.