gpt4 book ai didi

javascript - 用第二个数组中的匹配属性替换一个数组中的值

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

我有两个数组:

arrayOne = ["green","blue","purple"]

arrayTwo = [
{ name: "green", id: 1 },
{ name: "red", id: 2 },
{ name: "yellow", id: 3 },
{ name: "blue", id: 8 },
]

我希望返回数组为 [1, 8, 9],“purple”作为对象被推送到 arrayTwo 的末尾(使用新的编号)。

解决此问题的最有效方法是什么?

最佳答案

以下代码使用 map 检索第二个数组中元素的 id,或者如果该元素不存在,则通过递增创建一个新元素该数组中的最后一个 id 加 1。

arrayOne = ["green","blue","purple"]

arrayTwo = [
{ name: "green", id: 1 },
{ name: "red", id: 2 },
{ name: "yellow", id: 3 },
{ name: "blue", id: 8 },
]

const newArr = arrayOne.map(color => {
const found = arrayTwo.find(el => el.name === color);
if (found) {
return found.id;
}
const newId = arrayTwo[arrayTwo.length - 1].id + 1;
arrayTwo.push({ name: color, id: newId });
return newId;
});

console.log(newArr);

console.log(arrayTwo);

编辑:请注意,假设 arrayTwo 中的最后一项包含最高 ID 可能会很脆弱。在这种情况下,您总能找到最大 ID:

const newArr = arrayOne.map(color => {
let maxId = 0;
const found = arrayTwo.find(el => {
if (el.id > maxId) {
maxId = el.id;
}
return el.name === color
});
if (found) {
return found.id;
}
const newId = maxId + 1;
arrayTwo.push({ name: color, id: newId });
return newId;
});

关于效率的思考

如果这将是一个大型(数百/数千/更多)元素数组,如果您担心效率,您可以考虑将 arrayTwo 更改为以颜色作为键的对象:

const arrayOne = ["green","blue","purple"];

const arrayTwo = [
{ name: "green", id: 1 },
{ name: "red", id: 2 },
{ name: "yellow", id: 3 },
{ name: "blue", id: 8 },
];

let maxId = 0;

// Create map
const arrayTwoMap = arrayTwo.reduce((acc, el) => {
if (el.id > maxId) maxId = el.id;
acc[el.name] = el.id;
return acc;
}, {});

// Find elements
const newArr = arrayOne.map(el => {
const found = arrayTwoMap[el];
if (found !== undefined) {
return found;
}
const newId = maxId + 1;
arrayTwoMap[el] = newId;
return newId;
});

console.log(newArr);

关于javascript - 用第二个数组中的匹配属性替换一个数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59024484/

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