我正在尝试对数组进行排序.
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);
当我尝试对其进行排序时,名称10"首先出现,但名称3"应该首先出现.
When I try to sort it, "Name 10" comes first but "Name 3" should come fist.
我也尝试过-
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 });还有-
Array.prototype.reverse() String.prototype.localeCompare()developer.mozilla/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
但是仍然没有运气.谁能指出这里出什么问题了?
But still no luck. Can anyone point out whats wrong here?
推荐答案为什么不起作用?
您正在对字符串进行排序,默认排序为词典顺序.您正在寻找的是按自然顺序排序.
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.
您可以使用 > String#localeCompare 进行自然排序.
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);