使用javascript按特定顺序对具有十进制值的数组进行排序

问题描述 投票:0回答:3

我有一个数组:

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

排序后得到输出:

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

但我希望它像页面索引一样排序:

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

编辑: 我没有什么好的解决方案,但它们缺少一个地方,例如:

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

结果会是这样的:

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

这里的预期是:

[ "77", "77.8", "77.9", "77.11", "77.12", "88", "100", "100.8", "100.11", "100.12", "100.9", "119", "120"]
javascript arrays typescript sorting
3个回答
5
投票

您可以使用

string#localeCompare
numeric
属性来根据数值对数组进行排序。

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)


0
投票

不是简单的单行。您想首先按整数部分排序,然后如果相等,则按小数部分排序。

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


0
投票

要按数字和小数部分对数字进行比较和排序,您可以创建自定义排序,首先检查整数部分是否不相等,然后比较如果不相等,然后比较然后比较它们的小数部分:

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

function customSort(a, b) {
    const [aInt, aDec] = a.split('.').map(Number);
    const [bInt, bDec] = b.split('.').map(Number);

    // Compare the integer parts first
    if (aInt !== bInt) {
        return aInt - bInt;
    }

    // If the integer parts are equal, compare the decimal parts
    return aDec - bDec;
}

arr.sort(customSort);

console.log(arr);

© www.soinside.com 2019 - 2024. All rights reserved.