gpt4 book ai didi

javascript - 如何使用键和排序顺序对嵌套数组进行排序

转载 作者:行者123 更新时间:2023-11-30 13:59:18 24 4
gpt4 key购买 nike

我正在尝试根据键和排序顺序对嵌套数组实现多重排序。

我可以根据键和顺序对数组进行排序

我已经完成了以下用于对数组进行排序的代码,

return array.sort((a, b) => {
let i = 0, result = 0;
while (i < sortBy.length && result === 0) {
if (typeof a[sortBy[i].prop] == "string") {
result = sortBy[i].direction * (a[sortBy[i].prop].toString() < b[sortBy[i].prop].toString() ? -1 : (a[sortBy[i].prop].toString() > b[sortBy[i].prop].toString() ? 1 : 0));
} else {
result = sortBy[i].direction * (a[sortBy[i].prop] < b[sortBy[i].prop] ? -1 : (a[sortBy[i].prop] > b[sortBy[i].prop] ? 1 : 0));
}
i++;
}
return result;
});

我的输入数据如下,

array = [{ x: [{ d: 4 }, { d: 2 }, { d: 3 }, { d: 1 }], b: 'v' }, { x: [{ d: 8 }, { d: 7 }, { d: 5 }, { d: 6 }], b: 's' }];
sortBy= [{ 'prop': 'b', 'direction': 1 }, { 'prop': 'd', 'direction': 1}];

我希望得到如下输出,

array = [{ x: [{ d: 5 }, { d: 6 }, { d: 7 }, { d: 8 }], b: 's' },{ x: [{ d: 1 }, { d: 2 }, { d: 3 }, { d: 4 }], b: 'v' }];

但我得到以下结果,

array = [{ x: [{ d: 8 }, { d: 7 }, { d: 5 }, { d: 6 }], b: 's' },{ x: [{ d: 4 }, { d: 2 }, { d: 3 }, { d: 1 }], b: 'v' }];

我一直在思考如何解决这个逻辑问题。谁能帮我解决这个问题。

最佳答案

你很接近,你要做的是在具有属性 x 的内部数组上调用你的排序方法。然后后记在原始数组上调用它。这将首先使用 d 属性对子数组进行排序,然后通过 b 对外部数组进行排序。

array = [{ x: [{ d: 4 }, { d: 2 }, { d: 3 }, { d: 1 }], b: 'v' }, { x: [{ d: 8 }, { d: 7 }, { d: 5 }, { d: 6 }], b: 's' }];
sortBy= [{ 'prop': 'b', 'direction': 1 }, { 'prop': 'd', 'direction': 1}];

function sortFunc(a, b) {
let i = 0, result = 0;
while (i < sortBy.length && result === 0) {
if (typeof a[sortBy[i].prop] == "string") {
result = sortBy[i].direction * (a[sortBy[i].prop].toString() < b[sortBy[i].prop].toString() ? -1 : (a[sortBy[i].prop].toString() > b[sortBy[i].prop].toString() ? 1 : 0));
} else {
result = sortBy[i].direction * (a[sortBy[i].prop] < b[sortBy[i].prop] ? -1 : (a[sortBy[i].prop] > b[sortBy[i].prop] ? 1 : 0));
}
i++;
}
return result;
}

array.forEach(arr => arr.x = arr.x.sort(sortFunc));
array = array.sort(sortFunc);
console.log(array);

关于javascript - 如何使用键和排序顺序对嵌套数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644947/

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