【问题标题】:Comparing Two Arrays with Array.filter and Pushing to New Arrays Based on Common Values使用 Array.filter 比较两个数组并根据共同值推送到新数组
【发布时间】:2020-01-24 06:42:59
【问题描述】:

我正在尝试使用array.filter() 来比较两个数组并根据某个属性 (id) 分离出两个数组共有的值,而不是它们没有共同点的值。我要推送到新数组(recordsToUpdate)的常见 id。我想将剩余的元素从arr2 推送到一个新数组(recordsToInsert)。

我尝试过的方法不起作用。我怎样才能重做这个以获得我想要的结果? - (在这里的示例中应该是一个包含 1 个公共元素 {id: 3} 的数组,以及来自 arr2 的其余元素的另一个数组):

const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 3}, {id: 4}, {id: 5}];

let recordsToUpdate = [];
let recordsToInsert = [];

recordsToUpdate = arr1.filter(e => (arr1.id === arr2.id));
recordsToInsert = ?

console.log('recordsToUpdate: ', recordsToUpdate);
console.log('recordsToInsert: ', recordsToInsert);

期望的结果应该是:

recordsToUpdate = [{id: 3}];
recordsToInsert = [{id: 4}, {id: 5}];

【问题讨论】:

  • 请同时添加想要的结果。
  • 好的,我已经添加了想要的结果。两个数组之间有一个重叠值。更新了正确的信息。

标签: javascript arrays ecmascript-6


【解决方案1】:

试试这个,它使用Array.prototype.find 来测试一个对象是否存在于arr2 和给定的id

const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 3}, {id: 4}, {id: 5}];

const recordsToUpdate = arr1.filter(e => arr2.find(obj => obj.id === e.id) !== undefined);
const recordsToInsert = arr1.filter(e => arr2.find(obj => obj.id === e.id) === undefined);

console.log('recordsToUpdate: ', recordsToUpdate);
console.log('recordsToInsert: ', recordsToInsert);

【讨论】:

  • 我明白了,您必须划定 obj 才能定位该属性。说得通。非常感谢,@Robin。
【解决方案2】:

使用some 代替find 更新Robin 帖子。它只是另一种方式。

const arr1 = [{id: 1}, {id: 2}, {id: 3}];
const arr2 = [{id: 3}, {id: 4}, {id: 5}];

const recordsToUpdate = arr1.filter(e => arr2.some(obj => obj.id === e.id));
const recordsToInsert = arr2.filter(e => !arr1.some(obj => obj.id === e.id));

console.log('recordsToUpdate: ', recordsToUpdate);
console.log('recordsToInsert: ', recordsToInsert);

【讨论】:

  • 哈,谢谢 - 我很确定一定有一些 ES6 数组方法可以让这更简单,但由于某种原因不记得 some
【解决方案3】:

我认为这就是您所追求的...我添加了值以显示替换。如果您正在执行任何类型的状态管理,请小心,因为我正在直接改变当前数组。

const arr1 = [
  { id: 1, v: "a" },
  { id: 2, v: "b" },
  { id: 3, v: "old" }
];
const arr2 = [
  { id: 3, v: "new" },
  { id: 4, v: "e" },
  { id: 5, v: "f" }
];

function updateRecords(currentArray, updatesArray) {
  const currentIds = currentArray.map(item => item.id);

  updatesArray.forEach(updateItem =>
    currentIds.includes(updateItem.id)
      ? (currentArray[
          currentIds.findIndex(id => id === updateItem.id)
        ] = updateItem)
      : currentArray.push(updateItem)
  );

  return currentArray;
}

console.log(updateRecords(arr1, arr2))

现在提供以下选项:

[
  {
    "id": 1,
    "v": "a"
  },
  {
    "id": 2,
    "v": "b"
  },
  {
    "id": 3,
    "v": "new"
  },
  {
    "id": 4,
    "v": "e"
  },
  {
    "id": 5,
    "v": "f"
  }
]

将它放入函数中也是您可能想要做的事情,因为您可能会在代码中的多个位置使用它。

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多