Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array with duplicate values using Array.prototype.sort()?

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!

like image 470
kdizzle Avatar asked Jun 23 '26 14:06

kdizzle


1 Answers

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))
like image 97
Maheer Ali Avatar answered Jun 25 '26 04:06

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!