how to sort array which contains numbers? [duplicate]

为君一笑 提交于 2021-02-04 19:34:10

问题


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?


回答1:


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);



回答2:


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) {
  var nameA = a.label.toUpperCase(); // ignore upper and lowercase
  var nameB = b.label.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});

console.log(arr);



回答3:


There is a problem with your dataset.

You are sorting based on the label value which is a string. Strings are always sorted in a lexicographical order. If you would like "Name 3" to come before "Name 10" you can either use "Name 03" or better yet add another numerical attribute that will be used for sorting e.g.

{label: "Name 3", order: 3}



来源:https://stackoverflow.com/questions/47883859/how-to-sort-array-which-contains-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!