gpt4 book ai didi

javascript - 在 JavaScript 中对字符串类型的列进行排序

转载 作者:行者123 更新时间:2023-11-30 07:51:33 24 4
gpt4 key购买 nike

我想知道如何对具有数字或“x”值(未定义)的列进行排序。使用传统排序,结果不正确,17 比 7 早。

例子:

17   
7
9
X

想要这样排序:

7    
9
17
X

附言。
我正在使用:

var data = new google.visualization.DataTable()
data.addRow[{v:'17'}, {v:'7'}, {v:'9'}, {v:'X'}]

我希望能够在事件监听器中对其进行排序。

最佳答案

您可以在比较函数中使用 localeCompare{numeric:true} 选项:

let arr = ["17","7","9","X"];

function comparator(a,b) {
return a.localeCompare(b, "en", {numeric:true});
}

console.log(
arr.sort(comparator)
)

如果你的数组是这种格式

[{ v: '17' }, { v: 'X' }, { v: '7' }, { v: '9' }];

你必须稍微调整一下比较器:

var arr = [{ v: '17' }, { v: 'X' }, { v: '7' }, { v: '9' }];

function comparator(a,b) {
return a.v.localeCompare(b.v, "en", {numeric:true});
}

console.log(JSON.stringify(
arr.sort(comparator)
))

关于javascript - 在 JavaScript 中对字符串类型的列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com