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

标签 javascript

我有两个数组:

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/

相关文章:

javascript - 如何使用 javascript 禁用和重新启用按钮?

javascript - React Native - 无法获取数组中的项目,或无法在列表中显示数组中的项目

javascript - 使用 jQuery 实现类似光标轨迹的效果

javascript - 关闭浏览器窗口/选项卡时如何删除 localStorage 项目?

javascript - 在javascript中合并两个对象,忽略未定义的值

javascript - 如何使用 Nodejs 将新 ID 递增并添加到 Json 数组树结构中的新节点

javascript - 如何根据输入字段数组验证禁用提交按钮

javascript - MongoDB 查询 : how to find if a string within a nested objects

javascript - 使用 webpack 进行 Karma 测试

TypeScript 文件中的 JavaScript 引用