0

What am I trying to achieve?

So I have an array which needs to be checked for duplicates and if a duplicate is found I want to display the duplicate found using console.log for now. I must add this this code is based within a function.

The user will then add to this array using some input within the frontend , which is I currently have completed but it is not needed to solve this problem.

Here is my Array below which i want to find if there are duplicates within it.

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

basically if an new array object has identical values then display the duplicate

I assume I will have to use a for loop using the .length function but i am unsure how to achieve my task.

Possible array data below

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

If you have any question just ask below. Thanks.

John
  • 171
  • 3
  • 19

1 Answers1

2

Below should do the trick. It will loop the array and check if we already have the item already. It will console.log as requested, but also leave you with an array of distinct and duplicate items to process as needed

Demo:

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);
Samuel Goldenbaum
  • 18,391
  • 17
  • 66
  • 104