gpt4 book ai didi

javascript - 对键为变量的对象数组进行排序

转载 作者:行者123 更新时间:2023-12-02 14:11:33 25 4
gpt4 key购买 nike

我有以下结构:

var arrOfObjects = [
{
folder: {id: 2},
children: []
},
{
file: {id: 3},
children: []
},
{
file: {id: 4},
children: []
},
{
folder: {id: 1},
children: []
},
];

我想使用以下函数调用对其进行排序:

sortArrOfObjects(arrOfObjects, {
types: [
['file']
],
index: 'id',
order: 'asc'
});
sortArrOfObjects(arrOfObjects, {
types: [
['folder']
],
index: 'id',
order: 'asc'
});

输出将首先是文件的排序数组,然后是文件夹,例如:

var arrOfObjects = [
{
file: {id: 3},
children: []
},
{
file: {id: 4},
children: []
},
{
folder: {id: 1},
children: []
},
{
folder: {id: 2},
children: []
},
];

所以我有以下函数,在数组上调用 sort() 内置函数,并比较给定键存在的对象,并跳过其中一个键不存在的迭代比较器。但它不起作用,它似乎按完全错误的顺序排序。怎么了?

function sortArrayOfObjects(arr, sortBy) {
arr.sort(function (a, b) {
var first = '';
var second = '';
for (var i = 0; i < sortBy.types.length; i++) {
switch (sortBy.types[i].length) {
case 1:
if (a[sortBy.types[i][0]] != undefined) {
first = a[sortBy.types[i][0]][sortBy.index].toString().toLowerCase();
} else {
return;
}
if (b[sortBy.types[i][0]] != undefined) {
second = b[sortBy.types[i][0]][sortBy.index].toString().toLowerCase();
} else {
return;
}
break;
case 2:
// not implemented yet
break;
default:
break;
}
}
if (first > second) {
return (sortBy.order == 'asc') ? 1 : -1;
}
if (first < second) {
return (sortBy.order == 'asc') ? -1 : 1;
}
return 0;
});
};

最佳答案

称为“装饰-排序-取消装饰”的技术使这样的工作变得简单:

var arrOfObjects = [
{
folder: {id: 2},
children: []
},
{
file: {id: 3},
children: []
},
{
file: {id: 4},
children: []
},
{
folder: {id: 1},
children: []
},
];

result = arrOfObjects
.map(obj => ('file' in obj) ? [1, obj.file.id, obj] : [2, obj.folder.id, obj])
.sort((a, b) => a[0] - b[0] || a[1] - b[1])
.map(x => x[2]);


console.log(result)

基本上,我们将 [item, item...] 之类的数组转换为数组 [ [sort-keys, item], [sort-keys, item]... ,然后对该数组进行排序,最后以正确的顺序将我们的项目拉回来。

关于javascript - 对键为变量的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39511492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com