gpt4 book ai didi

javascript - 根据另一个对象数组的属性值对数组进行排序

转载 作者:行者123 更新时间:2023-12-01 15:51:40 25 4
gpt4 key购买 nike

假设我有一个对象数组:

var list = [
{ name: "A", distance: 1},
{ name: "B", distance: 2},
{ name: "C", distance: 3},
{ name: "D", distance: 4},
{ name: "E", distance: 5},
{ name: "F", distance: 6},
{ name: "G", distance: 7},
{ name: "H", distance: 8}
];

如果我有另一个像这样的数组:

var disturbed = ["G", "B", "C", "F"];

如何根据 list array 中的 distance 属性disturbed array 进行排序,如下所示:

["B", "C", "F", "G"];

编辑:我试过这段代码没有成功:

items = [ 
{ name: "A", distance: 1},
{ name: "B", distance: 2},
{ name: "C", distance: 3},
{ name: "D", distance: 4},
{ name: "E", distance: 5},
{ name: "F", distance: 6},
{ name: "G", distance: 7},
{ name: "H", distance: 8}
]

sorting = [ 1, 2,3,4,5,6,7,8,9,10 ];
result = []
for (let i = 0; i < items.length; i++){
sorting.forEach(function(key) {
var found = false;
items = items.filter(function(item) {

if(!found && items[i].distance == key) {
result.push(item);
found = true;
return false;
} else
return true;
})
})

result.forEach(function(item) {
document.writeln(item[i])
})
}

如何根据另一个对象数组的属性值对数组进行排序

最佳答案

您可以使用 .reduce()list 数组更改为对象,然后根据该对象进行排序。

演示:

var list = [
{ name: "A", distance: 1},
{ name: "B", distance: 2},
{ name: "C", distance: 3},
{ name: "D", distance: 4},
{ name: "E", distance: 5},
{ name: "F", distance: 6},
{ name: "G", distance: 7},
{ name: "H", distance: 8}
];

var disturbed = ["G", "B", "C", "F"];

var sort = list.reduce((acc, cur) => {
acc[cur.name] = cur.distance;
return acc;
}, {});

disturbed.sort((a, b) => sort[a] - sort[b]);

console.log(disturbed)

关于javascript - 根据另一个对象数组的属性值对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346424/

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