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;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745672088a4639465.html
评论列表(0条)