I am trying to sort an array.
Ex-
let arr = [{label: "Name 5"}, {label: "Name 3"},{label: "Name 12"}, {label: "Name 10"}, {label: "First Name 5"}, {label: "Apple"}, {label: "Orange"}, {label: "water"}];
let sortedArray = arr.sort(function(a, b){
return a.label.localeCompare(b.label);
});
console.log(sortedArray);
When I try to sort it, "Name 10" comes first but "Name 3" should come fist.
I have also tried this -
let sortedArray = arr.sort(function(a, b){
var nameA=a.label.toLowerCase(), nameB=b.label.toLowerCase();
if (nameA < nameB){
return -1;
} //sort string ascending
if (nameA > nameB){
return 1;
}
return 0; //no sorting
});
And this -
Array.prototype.reverse()
String.prototype.localeCompare()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
But still no luck. Can anyone point out whats wrong here?
You are sorting strings and the default sorting is lexicographical order. What you are looking for is sorting by natural order.
You could use the options of String#localeCompare
for natural sorting.
let arr = [{label: "Name 5"}, {label: "Name 3"},{label: "Name 12"}, {label: "Name 10"}, {label: "First Name 5"}, {label: "Apple"}, {label: "Orange"}, {label: "water"}];
arr.sort(function(a, b) {
return a.label.localeCompare(b.label, undefined, { numeric: true, sensitivity: 'base' });
});
console.log(arr);
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