sorting array with decimal value in specific order

2020-03-30 06:17发布

问题:

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"]

回答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)



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



回答3:

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);