Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to sort array by numbers first and then letters last

I am trying to sort an array. I am trying to sort by "itemCommodity". I need to sort by numbers only first and then numbers with letters last. For example:

1000 A120 B330 2020 J954 5000

Should be displayed as:

1000 2020 5000 A120 B330 J954

I hope someone can help me out with this. I have an example of what i was trying below but it does not work as expected.

var product_data = [{
"itemCommodity": "1000",
},
{
"itemCommodity": "B330",
},
{
"itemCommodity": "A120",
},
{
"itemCommodity": "J954",
},
{
"itemCommodity": "5000",
},
{
"itemCommodity": "2020",
}]

 product_data.sort(function(a, b) {
     return a.itemCommodity - b.itemCommodity;
 });

Please note that itemCommodity is not the only object in the array. I have about 40 different objects, just trying to sort on itemCommodity.

like image 968
Tom Avatar asked Dec 03 '22 13:12

Tom


2 Answers

Firstly sort the elements which doesn't contain any letter. Then - sort the rest comparing their first character.

var product_data = [{a:"1000"},{a:"B330"},{a:"A120"},{a:"J954"},{a:"5000"},{a:"2020"}],
    x = product_data.sort(function(a, b) {
      return /[A-Za-z]/.test(a.a) - /[A-Za-z]/.test(b.a) || a.a.charCodeAt(0) - b.a.charCodeAt(0)
    });

    console.log(x);

In case that you have simultaneously lowercase and uppercase letters, you will have to transform them all into one, mutual case and then sort them:

var product_data = [{a:"1000"},{a:"B330"},{a:"a120"},{a:"J954"},{a:"5000"},{a:"2020"}],
    x = product_data.sort(function(a, b) {
      return /[A-Za-z]/.test(a.a) - /[A-Za-z]/.test(b.a) || (a.a.toUpperCase() < b.a.toUpperCase() ? -1 : a.a.toUpperCase() > b.a.toUpperCase() ? 1 : 0)
    });

    console.log(x);
like image 95
kind user Avatar answered Mar 15 '23 04:03

kind user


You can try to compare them like this

product_data.sort(function(a, b) {
     return a.itemCommodity > b.itemCommodity;
});

And if you want the order of the letters to be sorted then you can try this

 product_data.sort(function(a, b) {
     return a.itemCommodity.toLowerCase() > b.itemCommodity.toLowerCase();
});
like image 24
todes Avatar answered Mar 15 '23 05:03

todes