【问题标题】:How to find a duplicate in an array of objects in JavaScript? [duplicate]如何在 JavaScript 中的对象数组中查找重复项? [复制]
【发布时间】:2020-03-11 04:05:00
【问题描述】:

我想达到什么目的?

所以我有一个需要检查重复的数组,如果发现重复,我现在想显示使用 console.log 找到的重复。我必须添加这个代码是基于一个函数。

然后用户将使用前端中的一些输入添加到这个数组中,这是我目前已经完成的,但不需要解决这个问题。

这是我的数组,我想在下面查找其中是否有重复项。

  const repeatedNumEvent = {
      PlayerNumber: this.state.PlayerNumber,
      eventType: this.state.eventType
    };

基本上如果一个新数组对象具有相同的值,则显示重复项

我假设我必须使用 .length 函数使用 for 循环,但我不确定如何完成我的任务。

下面可能的数组数据

{PlayerNumber: "12", eventType: "Goal"}

如果您有任何问题,请在下方提问。谢谢。

【问题讨论】:

  • 请贴一个数组数据的例子
  • 这不是一个真正的反应问题吗?
  • 道歉@dwjohnston,只是一种习惯,哈哈
  • @Chev 我已经为你更新了我的描述。这是我使用 console.log() 得到的一个例子
  • 请给我们看一些代码。我没有看到任何数组,而是一个具有两个属性的简单对象。

标签: javascript arrays duplicates


【解决方案1】:

下面应该可以解决问题。它将循环数组并检查我们是否已经拥有该项目。它会根据要求console.log,但也会为您留下一系列不同且重复的项目,以便根据需要进行处理

演示:

const data = [
    {PlayerNumber: "13", eventType: "Goal"},
    {PlayerNumber: "13", eventType: "Goal"},
    {PlayerNumber: "12", eventType: "Goal"},
    {PlayerNumber: "12", eventType: "Goal"},
    {PlayerNumber: "14", eventType: "Goal"}
];

let distinct = [];
let duplicates = [];
data.forEach((item, index, object) => {
    if (distinct.find(current => current.PlayerNumber === item.PlayerNumber && current.eventType === item.eventType)) {
        console.info('duplicate found');

        duplicates.push(item);
    } else {
        distinct.push(item);
    }
});

console.info('duplicates:', duplicates);
console.info('distinct:', distinct);

【讨论】:

  • 也可以使用 lodash _.isEqual 来比较对象
  • 当然,这次想保持原味,但强烈推荐lodash
猜你喜欢
  • 2014-08-08
  • 2018-12-18
  • 2019-04-28
  • 2021-11-14
  • 2014-01-26
  • 1970-01-01
  • 2019-01-02
相关资源
最近更新 更多