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 comparisons? I would like to achieve this using Array.prototype.sort and not have to write my own sort function.
Thanks!
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With