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?