首页 > 解决方案 > 在javascript中按多个对象属性对数组进行排序

问题描述

var array  = [
    {
        "checked": true,
        "name":"Name",
        "type": {
            "id": 1,
            "tag": "tag"
        }
    },
    {
        "checked": true,
        "name":"Name",
        "type": {
            "id": 3,
            "tag": "tag"
        }
    },
    {
        "checked": false,
        "name":"Name",
        "type": {
            "id": 2,
            "tag": "tag"
        }
    },
];

我想通过检查和 type.id 对数组进行排序。我使用以下排序代码,但“type.id”似乎有问题,因为如果选中,我的列表没有按那些分组。

sortByPriority(array, ['checked', 'type.id']);

sortByPriority(data, priorities) {
    if (priorities.length == 0 || data.length == 0) {
        return data;
    }
    const nextPriority = priorities[0];
    const remainingPriorities = priorities.slice(1);
    const matched = data.filter(item => item.hasOwnProperty(nextPriority));
    const remainingData = data.filter(item => !item.hasOwnProperty(nextPriority));

    return this.sortByPriority(matched, remainingPriorities)
        .sort((a, b) => (a[nextPriority] > b[nextPriority]) ? 1 : -1)
        .concat(this.sortByPriority(remainingData, remainingPriorities));
}

关于如何对类型对象进行排序的任何想法?

(我无法找到另一个问题,其答案是通用排序器能够根据数组中的对象进行排序)

标签: javascriptarrayssorting

解决方案


您可以对嵌套属性使用嵌套方法,并采用一组函数来比较值。

function sortByPriority(array, keys, fn) {

    function getValue(o, k) {
        return k.split('.').reduce((p, l) => (p || {})[l], o);
    }

    return array.sort((a, b) => {
        var d;
        keys.some((k, i) => d = fn[i](getValue(a, k), getValue(b, k)));
        return d;
    });
}

var array = [{ checked: false, name: "Name", type: { id: 2, tag: "tag" } }, { checked: true, name: "Name", type: { id: 3, tag: "tag" } }, { checked: true, name: "Name", type: { id: 1, tag: "tag" } }];

sortByPriority(array, ['checked', 'type.id'], [(a, b) => b - a, (a, b) => a - b]);

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


推荐阅读