在javascript中按多个键和多个订单排序

时间:2014-12-08 17:56:35

标签: javascript sorting

我需要对一组对象进行排序,提供带有键及其顺序的字典。 就像这样:

var data = [
    { "name": "a", "age": 1, "money": 4 },
    { "name": "f", "age": 4, "money": 1 },
    { "name": "c", "age": 2, "money": 3 },
    { "name": "a", "age": 0, "money": 1},
    { "name": "f", "age": 4, "money": 3 },
    { "name": "c", "age": 1, "money": 4 },
    { "name": "c", "age": 3, "money": 1 }
];

var data = data.multiSort({
    name: "asc",
    age: "desc",
    money: "desc"
});

console.log(data);
/*
{ "name": "a", "age": 1, "money": 4 },
{ "name": "a", "age": 0, "money": 1},
{ "name": "c", "age": 3, "money": 1 }
{ "name": "c", "age": 2, "money": 3 },
{ "name": "c", "age": 1, "money": 4 },
{ "name": "f", "age": 4, "money": 3 },
{ "name": "f", "age": 4, "money": 1 }
*/

我完全陷入困境,我不知道如何实现这一目标。很多人指出这段简单的代码,但我不明白它应该如何实现我想要做的事情。 https://github.com/Teun/thenBy.js

这是我现在的代码。我知道我离解决方案很远,但我很感激任何帮助,以了解如何实现这一目标,因为我需要在javascript上进行大量改进。

Array.prototype.multiSort = function(sorters){

    function getNextSorter(sorters, currentSorterKey) {
        var sortersKeys = Object.keys(sorters);
        if(!currentSorterKey)
            currentSorterIndex = 0;
        else
            currentSorterIndex = sortersKeys.indexOf(currentSorterKey) + 1;

        var key = sortersKeys[currentSorterIndex];
        var order = sorters[key];
    }

    function compare(a, b, key, order) {
        var a = a[key];
        var b = b[key];

        //if both numbers compare them as numbers and not as strings
        var numericA = parseFloat(a);
        var numericB = parseFloat(b);
        if(!isNaN(numericA) && !isNaN(numericB)) {
            a = numericA;
            b = numericB;
        }

        //if different compare them with the given order
        if(a != b)
            return (order == "asc") ? a - b : b - a;
        //else compare next key as specified in sorters (if next key is present!)
        else
            //how to recursively call to get the next compare function?
    }

    //how to call sort now?

    return this;
};

2 个答案:

答案 0 :(得分:3)

为了使这项工作可靠,您将不得不改变接收数据的方式。对象不保证枚举的顺序,因此它可能会让外观工作一段时间,但它可能随时失败。

而是使用其他格式。下面我将使用带有:分隔符的字符串。像这样:

Array.prototype.multiSort = function() {
    // Make an array of arrays:
    // [  ["name" :"asc" ],
    //    ["age"  :"desc"],
    //    ["money":"desc"]   ]
    var sorters = Array.prototype.map.call(arguments, function(s) {
        return s.split(":");
    });

    function compare(a, b) {
        // Iterate over the sorters, and compare using the first non-equal values.
        for (var i = 0; i < sorters.length; i++) {
            var a_val = a[sorters[i][0]];
            var b_val = b[sorters[i][0]];
          
            if (a_val === b_val) {
                continue; // They're equal values, so try the next sorter
            }
            // Swap values if not ascending
            if (sorters[i][1] !== "asc") {
                var temp = a_val;
                a_val = b_val;
                b_val = temp;
            }
            // Use `.localeCompare()` if they're both strings
            if (typeof a_val === "string" && typeof b_val === "string") {
                return a_val.localeCompare(b_val);
            }
            return a_val - b_val;
        }
    }

    return this.sort(compare);
};

var data = [
    { "name": "a", "age": 1, "money": 4 },
    { "name": "f", "age": 4, "money": 1 },
    { "name": "c", "age": 2, "money": 3 },
    { "name": "a", "age": 0, "money": 1 },
    { "name": "f", "age": 4, "money": 3 },
    { "name": "c", "age": 1, "money": 4 },
    { "name": "c", "age": 3, "money": 1 }
];

var data = data.multiSort("name:asc", "age:desc", "money:desc");

document.body.innerHTML = "<pre>" + JSON.stringify(data, null, 4) + "</pre>";

所以它的作用是将每个字符串拆分为:,以便我们得到一个结果数组,其中包含要排序的键和方向。

然后在compare函数中,我们只是遍历sorters,从ab获取值,如果它们不相等,我们就去提前并返回比较。如果他们是平等的,我们需要转到下一个分拣机并尝试使用那个。

所以不需要额外的功能。只需for循环即可。

答案 1 :(得分:1)

thenBy script很酷。非常小,但效果很好。这是一个使用它的例子。不像其他示例那样可扩展,但可能值得考虑扩展以使其更具可重用性。

这里的主要内容是您通过了3种不同的排序功能。

// This sorts the name in ASC order
firstBy(function(d1, d2) { 
    if(d1.name < d2.name) return -1; 
    if(d1.name > d2.name) return 1;
    return 0;
})
// this sorts the age in DESC
// note that the > returns -1 but the < returns 1.
// flip these to sort in ASC
.thenBy(function(d1, d2) { 
    if(d1.age > d2.age) return -1;
    if(d1.age < d2.age) return 1;
    return 0;
 })
 // finally sort money in DESC order
 .thenBy(function(d1, d2) { 
    if(d1.money > d2.money) return -1;
    if(d1.money < d2.money) return 1;
    return 0;
 })

Here is a jsFiddle