Sorting Array With Decimal 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 indexi
Solution 1:
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)
Solution 2:
Not a simple oneliner. You wanna sort by the integer part first, then if that is equal, by the decimal part.
const arr = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9'];
const sorted = arr.sort((a, b) => {
if (parseInt(a) !== parseInt(b)) {
returnparseInt(a) - parseInt(b);
}
return (parseInt(a.split('.')[1], 10) || 0) - (parseInt(b.split('.')[1], 10) || 0);
});
console.log(sorted);
Post a Comment for "Sorting Array With Decimal Value In Specific Order Using Javascript"