简体   繁体   中英

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 indexing :

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

EDIT: I have got few good solution but they are lacking at one place ex: 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"]

here expected is :

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

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) 

You are sorting strings,one solution is to convert to float array:

 const arr = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9']; var floatArray = arr.map(function(elem) { return parseFloat(elem); }); floatArray = floatArray.sort((a, b) => a - b); console.log("Float array sorted:") console.log(floatArray); //if you need an array of strings var stringArray = floatArray.map(function(elem) { return elem.toString(); }); console.log("String array sorted:") console.log(stringArray); 

Simplified version:

 const arr = ['100.12', '77.8', '88', '77.11', '77.12', '77.9', '77', '119', '120', '100.8', '100.11', '100', '100.9']; var sortedArray= arr.map(function(elem) {return parseFloat(elem); }) .sort((a, b) => a - b) .map(function(elem) {return elem.toString(); }); console.log(sortedArray); 

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)) { return parseInt(a) - parseInt(b); } return (parseInt(a.split('.')[1], 10) || 0) - (parseInt(b.split('.')[1], 10) || 0); }); console.log(sorted); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM