gpt4 book ai didi

Javascript - 如何根据第二个数组的顺序对一个数组进行比较和排序?

转载 作者:行者123 更新时间:2023-12-03 04:28:59 26 4
gpt4 key购买 nike

如果我有一个数组,其中包含一堆按旧方式排序的帖子:

[
{
id: 1,
name: "first parent post"
},
{
id: 2,
name: "second child of first parent post"
},
{
id: 3,
name: "second parent post"
},
{
id: 4,
name: "first child of first parent post"
},
{
id: 5,
name: "first child of second parent post"
}
]

但是,另一个数组根据第一个数组的 id 决定第一个数组的结构:

[
{
id: 1,
parent: 0
},
{
id: 4,
parent: 1
},
{
id: 2,
parent: 1
},
{
id: 3,
parent: 0
},
{
id: 5,
parent: 3
}
]

对这些进行排序以便第一个数组按第二个数组排序的最有效方法是什么?

我希望生成的数组看起来像这样:

[
{
id: 1,
name: "first parent post",
indent: 0
},
{
id: 4,
name: "first child of first parent post",
indent: 1
},
{
id: 2,
name: "second child of first parent post",
indent: 1
},
{
id: 3,
name: "second parent post",
indent: 0
},
{
id: 5,
name: "first child of second parent post",
indent: 1
}
]

最佳答案

您可以按索引对数据数组进行排序,然后按顺序数组进行排序;

要获得缩进,您必须跟踪上游父级的缩进并添加一个:

var data  = [
{
id: 1,
name: "first parent post"
},
{
id: 2,
name: "second child of first parent post"
},
{
id: 3,
name: "second parent post"
},
{
id: 4,
name: "first child of first parent post"
},
{
id: 5,
name: "first child of second parent post"
}
]

var ord = [
{
id: 1,
parent: 0
},
{
id: 4,
parent: 1
},
{
id: 2,
parent: 1
},
{
id: 3,
parent: 0
},
{
id: 5,
parent: 3
}

]
// first you arrange the data element by index
dataByIndex = data.reduce((ac, x) => {
ac[x.id] = x;
return ac
},[])

// then you order them by the ord array
var res = ord.reduce((ac, x, i) => {
var item = dataByIndex[x.id]
item.indent = x.parent === 0 ? 0 : getParentIndentPlusOne(ac, x.parent)

return [...ac, item]
}, [] )

function getParentIndentPlusOne(ac, id){
var i = ac.length
while (--i > -1){
if (id === ac[i].id) return ac[i].indent + 1
}
}



console.log(res)

关于Javascript - 如何根据第二个数组的顺序对一个数组进行比较和排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43576040/

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