【发布时间】:2022-02-15 17:29:22
【问题描述】:
我有两个数组。按 id 查找,从 Array1 IN Array2 中找到第一个出现的元素,获取在 Array2 中找到该元素的索引,并创建一个新数组,其中 Array1 中的元素移动到 Array2 中找到的新索引。在 Array1 {id: 001} 位于索引 0 处,我希望它位于索引 1 处的新数组中(索引它首先在 Array2 中找到)。 {id: 002} 在 Array1 中的索引 1 处,我希望它位于索引 3 处的新数组中(索引它首先在 Array2 中找到)等等....
const Array1 = [
{
id: '001',
school: "blue springs"
},
{
id: '002',
school: "sycamore hills"
},
{
id: '003',
school: "moreland ridge"
},
{
id: '004',
school: "grain valley"
}
]
const Array2 = [
{
id: '003',
participant: "Susan"
},
{
id: '001',
participant: "Henry"
},
{
id: '003',
participant: "Justin" <---- if 003 exists do not duplicate the return array, this is my issue....
},
{
id: '004',
participant: "Jessica"
},
{
id: '002',
participant: "Carly"
},
{
id: '001',
participant: "Chloe" <---- if 001 exists do not duplicate the return array, this is my issue....
}
// got this far,
const finder = Array1.map((el) => { return Array2.findIndex((el2) => { return el2.id === el.id}) })
console.log(finder)
// [ 1, 4, 0, 3 ] <--- need to move Array1 objects to these new indexes
预期输出
const Result = [
{
id: '003',
school: "moreland ridge"
},
{
id: '001',
school: "blue springs"
},
{
id: '004',
school: "grain valley"
},
{
id: '002',
school: "sycamore hills"
}
]
【问题讨论】:
-
嗯,我没有看到你已经尝试过的代码in your post?
-
请发布您的代码
-
刚刚添加了我到目前为止的内容
-
你希望发生什么 1) Array1 中的元素而不是 Array2 中的元素;和 2) Array2 中的元素不在 Array1 中
-
如果 Array1 的 id 在 array2 中不存在,则忽略它
标签: javascript arrays multidimensional-array