Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript .sort() skips over a value

Given the array of numbers

let el = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000];

The output of the following suggests that it ignores the value of 3000

let el = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000];
console.log(el.sort());

//Output [10000, 25000, 29000,3000, 33000, 40000,42000, 48000, 54000,57000, 79000, 86000]

So it did sort, but didn’t move the 3000 at the 4th position. Why is this happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As VLAZ explained, By default, the sort() function sorts values as strings. if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect results when sorting numbers.

You can fix this by providing a compare function: (a, b) => a - b)

let el = [25000,48000,57000,86000,33000,10000,42000,3000,54000,29000,79000,40000];
console.log(el.sort((a, b) => a - b));

checkout: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading