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.
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);
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With