'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.
Solution 1:[1]
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);
Solution 2:[2]
Since, as per ASCII table, numbers come first and then alphabets you can sort them using sort() method directly as follows;
["1000","A120","B330","2020", "J954", "5000"].sort()
results
["1000", "2020", "5000", "A120", "B330", "J954"]
However, as you don't have the array directly (given in your example), you can iterate all the nodes of JSON and compare them directly;
"1000" > "A120" => false; "1000" < "A120" => true
So there is just small correction in you code;
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;
});
console.log(product_data);
Solution 3:[3]
For sorting an array in JS what you are describing is default behaviour.
var myArray = ["123","A123","345","C123","B123"]
myArray.sort();
console.log(myArray);
Though for an associative array you may want to look at this post:
How to sort an associative array by its values in Javascript?
Solution 4:[4]
you can use map to create an array and sort it using sort.
var numArray = [];
var product_data = [{
"itemCommodity": "1000",
},
{
"itemCommodity": "B330",
},
{
"itemCommodity": "A120",
},
{
"itemCommodity": "J954",
},
{
"itemCommodity": "5000",
},
{
"itemCommodity": "2020",
}]
product_data.map(function(value, index) {
numArray.push(value["itemCommodity"]);
})
numArray.sort();
var newNum=(numArray.join(","));
alert(newNum);
Solution 5:[5]
I think this is sort of what you were looking for. It's kinda verbose, but it gets the job done. Assuming you do not know what the keys of the objects are this will sort the objects based on their values without prior knowledge of key. Sorts numbers first in ascending order and then strings in ascending order. You can change this order by changing the compare functions returns and the sort functions returns for numbers.
var numbersAlphAscending = (a, b) => {
// get unknown keys
var currentKeyA = Object.keys(a)[0];
var currentKeyB = Object.keys(b)[0];
// if item is a number
if (Number(a[currentKeyA]) && Number(b.itemCommodity)) {
return a[currentKeyA] - b[currentKeyB];
}
// if item is a string
if (!Number(a[currentKeyA]) && !Number(b[currentKeyB])) {
return a[currentKeyA].toLowerCase() > b[currentKeyB].toLowerCase();
}
// numbers before strings
return Number(a[currentKeyA]) ? -1 : 1;
}
var product_data = [{"itemCommodity": "1000",},{"itemCommodity": "B330",},{"itemCommodity": "A120",},{"itemCommodity": "J954",},{"itemCommodity": "5000",},{"itemCommodity": "2020",}]
console.log(product_data.sort(numbersAlphAscending));
Solution 6:[6]
reducethe array into two arrays- one without letters, another with letters- Sort the order of each array
- Finally, concat the two sorted array together
var product_data = [
{ "itemCommodity": "1000" },
{ "itemCommodity": "B330" },
{ "itemCommodity": "A120" },
{ "itemCommodity": "J954" },
{ "itemCommodity": "5000" },
{ "itemCommodity": "2020" }
];
product_data
// We reduce into two array - one without letters, another with letters
.reduce((arr, record) => {
const index = (record.itemCommodity.match(/[a-z]/i)) ? 1 : 0;
arr[index].push(record);
return arr;
}, [[],[]])
// We sort the two array respectively
.map((arr) => arr.sort((a,b) => a.itemCommodity > b.itemCommodity))
// We concat the two sorted array
.reduce((curr, next) => curr.concat(next));
console.log(product_data);
Solution 7:[7]
You can use localeCompare() method to sort the data. Reference
var product_data = [
{
itemCommodity: '1000',
},
{
itemCommodity: 'B330',
},
{
itemCommodity: 'A120',
},
{
itemCommodity: 'J954',
},
{
itemCommodity: '5000',
},
{
itemCommodity: '2020',
},
];
var sorted_data = product_data.sort(function (a, b) {
return a.itemCommodity.localeCompare(b.itemCommodity, undefined, {
numeric: true,
});
});
console.log(sorted_data);
Solution 8:[8]
You could try this small trick of string based comparison only when both values are non-numeric, else use numeric sorting.
var product_data = [{
"itemCommodity": "1000",
},
{
"itemCommodity": "B330",
},
{
"itemCommodity": "A120",
},
{
"itemCommodity": "J954",
},
{
"itemCommodity": "5000",
},
{
"itemCommodity": "2020",
}
];
product_data.sort(function(a, b) {
if(isNaN(a) || isNaN(b))
return a.itemCommodity.toLowerCase() > b.itemCommodity.toLowerCase();
else
return +a.itemCommodity.toLowerCase() > +b.itemCommodity.toLowerCase();
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Aá´ÉªÊ€ |
| Solution 3 | Community |
| Solution 4 | |
| Solution 5 | |
| Solution 6 | |
| Solution 7 | Ved |
| Solution 8 | Sheikh Azad |
