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"
}
},
];
我想按checked和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));
}
对如何对类型对象进行排序有什么想法吗?
(我还没能找到另一个问题的答案,这个问题的答案是能够根据数组中的对象进行排序的通用排序器)
发布于 2018-06-27 04:49:32
您可以对嵌套属性使用嵌套方法,并使用一个函数数组来比较这些值。
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; }
发布于 2018-06-27 04:35:11
在数组上重载sort
方法,然后就可以根据排序条件切换<
和>
。注意,我在第一次排序时删除了return 0
,以便在checked
值相等的情况下转移到第二次排序。
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"
}
},
];
function customSort(ob1, ob2) {
if (ob1.checked > ob2.checked) {
return 1;
} else if (ob1.checked < ob2.checked) {
return -1;
}
// Else sort on the second item
if (ob1.type.id < ob2.type.id) {
return -1;
} else if (ob1.type.id > ob2.type.id) {
return 1
} else {
return 0;
}
}
console.log(array);
console.log(array.sort(customSort));
https://stackoverflow.com/questions/51050842
复制相似问题