Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array with Integer and then by decimal section of value in specific order using javascript

I have an array:

let arr = ['100.12', '100.8', '100.11', '100.9'];

after sorting getting output:

'100.11', '100.12', '100.8', '100.9'

But I want it to be sorted like page indexing:

'100.8', '100.9', '100.11', '100.12',


EDIT: I have a few good solutions, but they are lacking in one place, for example:

arr1 = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9']

result would be like:

["77.8", "77.9", "77.11", "77.12", "77", "88", "100.8", "100.11", "100.12", "100", "100.9", "119", "120"]

What is expected is:

[ "77", "77.8", "77.9", "77.11", "77.12", "88", "100", "100.8", "100.11", "100.12", "100.9", "119", "120"]

like image 469
sumit sharma Avatar asked Jun 07 '26 09:06

sumit sharma


1 Answers

You can use string#localeCompare with numeric property to sort your array based on the numeric value.

let arr = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9'];
arr.sort((a, b) => a.localeCompare(b, undefined, {numeric: true}))
console.log(arr)
like image 136
Hassan Imam Avatar answered Jun 10 '26 04:06

Hassan Imam



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!