删除数组中的重复项,但添加一个计数 属性 以查看重复项的数量

Delete duplicates in an array but add a count property to see the number of duplicates

基本上如果我有这个数组:

[{"id" = 1, "product" = "Book"}, {"id" = 1, "product" = "Book"}, {"id" = 1, "product" = "Book"}, {"id" = 2, "product" = "Chair"}]

它会变成这个数组:

 [{"id" = 1, "product" = "Book", "count" = 3}, {"id" = 2, "product" = "Chair", "count" = 1}]

我正在使用 React。我的另一个选择是在制作和添加到数组时添加计数 属性,这样就不会添加重复项,但我很好奇是否有办法使用现有数组来做到这一点。

编辑: 如果两个产品具有相同的 ID,则它们是重复的。

我尝试过使用 id 过滤数组,然后获取第一个对象。我再次通过 id 过滤数组以获得长度。然后我向第一个对象添加了一个新的 属性 “count”,它是过滤后数组的长度,之后我将第一个对象添加到一个新数组中。 这样做的问题是我必须为每个可能的 id 硬编码,即使它不包含在我的数组中。

您可以将数组缩减为添加了 count 属性 的新数组。假定 id 属性 足以考虑唯一性。如果已经看到该元素,则增加 count,否则附加一个新的增强元素对象。

const data = [{
  "id": 1,
  "product": "Book"
}, {
  "id": 1,
  "product": "Book"
}, {
  "id": 1,
  "product": "Book"
}, {
  "id": 2,
  "product": "Chair"
}];

const dedupedData = data.reduce((data, el) => {
  const index = data.findIndex(item => item.id === el.id);
  if (index !== -1) {
    data[index].count++;
  } else {
    data.push({ ...el, count: 1 });
  }
  return data;
}, []);

console.log(dedupedData);

将数组缩减为由 id 键控的 Map(甚至只是一个普通对象)(假设这就是识别重复项所需的全部)。

该映射的值将是您要查找的数组。

const arr = [{"id":1,"product":"Book"},{"id":1,"product":"Book"},{"id":1,"product":"Book"},{"id":2,"product":"Chair"}]

const zipped = Array.from(arr.reduce((map, o) => {
  // check if id already registered
  if (map.has(o.id)) {
    // increment count
    map.get(o.id).count++
  } else {
    // otherwise, store the new object with count starting at 1
    map.set(o.id, { ...o, count: 1 })
  }
  return map
}, new Map()).values())

console.log(zipped)
.as-console-wrapper { max-height:100% !important; }