admin管理员组文章数量:1435859
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. Andsort
does not return a new array. It mutates the existing array. – Eddie Commented May 2, 2019 at 2:38
2 Answers
Reset to default 3You 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;
}
本文标签: javascriptHow to sort an array with duplicate values using Arrayprototypesort()Stack Overflow
版权声明:本文标题:javascript - How to sort an array with duplicate values using Array.prototype.sort()? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745672087a2669630.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论