【问题标题】:Javascript alphabetical sortin; how do I compare numerical values as numbers, but compare those to also to strings?Javascript 字母排序;如何将数值作为数字进行比较,但也将它们与字符串进行比较?
【发布时间】:2018-04-04 18:26:23
【问题描述】:

我有一个要在图表中显示的数据列表,我希望这些数据按字母顺序显示。当数据点都是单词(例如“white”、“asian”、“african American”)时,我的排序功能可以正常工作,但是当我的数据点包含数字时(例如“1”、“10”、“

var series = response.series;

series = series.sort(function(a, b) {
    var textA = a.name.toLowerCase();
    var textB = b.name.toLowerCase();
    console.log("Comparing " + textA + " to " + textB);
    var returnVal = (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
    console.log(returnVal);
    return returnVal;
});

我可以从控制台日志中看到比较似乎正确比较,但是当我在排序后再次检查系列时,它和以前一样。这是我的数据的更大示例:

series = [
    {name: "1"}
    {name: "10"}
    {name: "11"}
    {name: "12"}
    {name: "13"}
    {name: "2"}
    {name: "3"}
    {name: "4"}
    {name: "5"}
    {name: "6"}
    {name: "7"}
    {name: "8"}
    {name: "9"}
    {name: "<1"}
    {name: "Total 18 and below"}
]

【问题讨论】:

  • 你是在排序字符串,而不是数字
  • 可能重复排序的东西数组,而不是对象数组,但听起来你要求一个字母数字排序实现。

标签: javascript jquery string sorting string-comparison


【解决方案1】:

我意识到这些值是作为字符串而不是数字进行比较的,在 Javascript 中,“123”在“2”之前,就像“abc”在“b”之前一样。我不能只将整个数组转换为数字,因为它包含“

series = series.sort(function(a, b) {
    var textA = a.name.toLowerCase();
    var textB = b.name.toLowerCase();

    // if we're comparing number to number, do number sorting
    if (!isNaN(textA) && !isNaN(textB)) {
        var numA = parseInt(textA);
        var numB = parseInt(textB);
        return (numA < numB) ? -1 : (numA > numB) ? 1 : 0;
    }

    // else sort as strings
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
});

【讨论】:

  • 我不太确定它会产生预期的结果,否则我误解了这个问题。例如,您希望如何对字符串 &lt;2, 3, &gt;4 进行排序,或者这是您不关心的情况?
  • 你运行你的代码了吗?(它没有给出正确的输出)
【解决方案2】:

您可以按数字排序,如果有比较符号可用,则将两个偏移量的增量取相同的数值,这反映了比较的顺序。

为了获得正确的测试顺序'and below',我建议将其替换为'&lt;=' 以获得正确的顺序。

var array = [{ name: "1" }, { name: "10" }, { name: "11" }, { name: "12" }, { name: "13" }, { name: "2" }, { name: "3" }, { name: "4" }, { name: "5" }, { name: "6" }, { name: "7" }, { name: "8" }, { name: "9" }, { name: "<1" }, { name: "Total 18 and below" }, { name: "> 18" }, { name: "18" }];

array.sort(function (a, b) {
    function getV(s) {
        s = s.replace(/(\D*)(\d+)\s*(and below)/i, '<= $2');
        return {
            value: s.match(/\d+/)[0],
            offset: { '<': -2, '<=': -1, null: 0, '>=': 1, '>': 2 }[s.match(/[<>]={0,1}(?=\s*\d)/)]
        };
    }
    var aa = getV(a.name),
        bb = getV(b.name);
    return aa.value - bb.value || aa.offset - bb.offset;
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    相关资源
    最近更新 更多