最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sort an array with duplicate values using Array.prototype.sort()? - Stack Overflow

programmeradmin1浏览0评论

I want to sort an array with duplicate values using the Array.prototype.sort().

For instance if I execute this [1, 2, 0, 1].sort((a, b) => a + b) to achieve a sorted array in descending order, I am returned back the same array [1, 2, 0, 1].

Why is this happening and how can I sort this array using Array.prototype.sort? Is javascript's Array sort not reliable for sorting through duplicate values or am I providing a function that isn't making the right parisons? I would like to achieve this using Array.prototype.sort and not have to write my own sort function.

Thanks!

I want to sort an array with duplicate values using the Array.prototype.sort().

For instance if I execute this [1, 2, 0, 1].sort((a, b) => a + b) to achieve a sorted array in descending order, I am returned back the same array [1, 2, 0, 1].

Why is this happening and how can I sort this array using Array.prototype.sort? Is javascript's Array sort not reliable for sorting through duplicate values or am I providing a function that isn't making the right parisons? I would like to achieve this using Array.prototype.sort and not have to write my own sort function.

Thanks!

Share Improve this question asked May 2, 2019 at 2:34 kdizzlekdizzle 6271 gold badge12 silver badges24 bronze badges 1
  • .sort((a, b) => a - b) maybe. And sort does not return a new array. It mutates the existing array. – Eddie Commented May 2, 2019 at 2:38
Add a ment  | 

2 Answers 2

Reset to default 3

You need to subtract the two values.

//ascending order
console.log([1, 2, 0, 1].sort((a, b) => a - b))

//descending order
console.log([1, 2, 0, 1].sort((a, b) => b - a))

The Reason, why it is not working is:

If you look into offical MDN Documentation,

The sort() method sorts the elements of an array in place and returns the array. The default sort order is built upon converting the elements into strings, then it pairs the array.

var months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

var array1 = [1, 2, 0, 1];
array1.sort((a, b) => a + b);
console.log(array1);
// expected output: Array [1, 2, 0 ,1]

So, To pare numbers instead of strings, the pare function can simply subtract b from a. The following function will sort the array ascending (if it doesn't contain Infinity and NaN)

function pareNumbers(a, b) {
  return a - b;
}

发布评论

评论列表(0)

  1. 暂无评论