JavaScript 排序函数未按预期工作

标签 javascript sorting

我正在尝试对数组进行排序:

var mapped = [{
    wiFi: true,
    megapixel: '20 MP'
},{
    wiFi: false,
    megapixel: '25 MP'
},{
    wiFi: true,
    megapixel: '25 MP'
},{
    wiFi: true,
    megapixel: '21 MP'
}];

我想对这两个属性进行排序(首先是 WiFi)。这是我正在做的事情的一个非常简单的版本,但属性可以由用户决定,所以我有一个看起来有点像这样的函数:

var fields = ['wiFi', 'megapixel'];

// Sort our mapped array
mapped.sort(function (a, b) {

    // Loop through our properties
    fields.forEach(function (field) {

        // Get our value (skip the first)
        var x = a[field.name];
        var y = b[field.name];

        // Switch on the type
        switch (typeof x) {

            // Boolean
            case "boolean":

                // Return our value
                return x === y ? 0 : x ? -1 : 1;

            // Default
            default:

                // Return our value
                return x === y ? 0 : x < y ? -1 : 1;

        }
    });
});

但我的数组根本没有排序。有谁知道为什么吗?

最佳答案

尝试手动迭代而不是使用内部函数的迭代。

mapped.sort(function(a,b) {
    var x, y, i, l = fields.length;
    for( i=0; i<l; i++) {
        x = a[fields[i]];
        y = b[fields[i]];
        if( x === y) continue; // proceed to next field to compare
        switch(typeof x) {
        case "boolean":
            return x ? -1 : 1;
        // could do other things, eg. case "string": return x.localeCompare(y);
        default:
            return x < y ? -1 : 1;
        }
    }
    return 0; // all fields compared equal
});

关于JavaScript 排序函数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912197/

相关文章:

ruby-on-rails - 按另一个 id 数组对 activerecord 结果集进行排序

javascript - 将 style.backgroundImage 更改为 php $_SESSION

javascript - Jquery .click 不会控制台日志或警报

javascript - 按键事件在第一次触发事件时不记录输入值

c - 降序不能正常工作c编程

c++ - 在 C++ 中对用户定义的结构进行排序

javascript - t :selectOneMenu how to get selected value using java script?

javascript - Jquery追加一个div并删除一个div

python - 如何先按值排序字典,然后按键排序

c# - 按多列对 C# 中的锯齿状数组进行排序