Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort array which contains numbers? [duplicate]

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?

like image 797
Joomler Avatar asked Dec 19 '22 02:12

Joomler


1 Answers

Why is it not working?

You are sorting strings and the default sorting is lexicographical order. What you are looking for is sorting by natural order.

Proposed solution

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);
like image 182
Nina Scholz Avatar answered Dec 29 '22 14:12

Nina Scholz