1

My data structure

I need to create a function to only display duplicate data from the first object that is a duplicate. If you look in my code I have an array with objects inside of it. My data structure is like this:

[
 { data: ["22409972", "1267304", "1000", "FG-18-1267304"] },
 { data: ["22409972", "1267304", "2000", "FG-18-1267304"] }
]

In this scenario I would not want to include the second object of data since its first index already exists in the first object "22409972"

I need a solution that could support having multiple duplicate objects with the same first index, still only wanting to return the first object containing the duplicate index

Essentially if a duplicate object exists remove it from the arrayThatContainsDuplicates array

I tried to use this as a solution

 const noDuplicates = [];
    for (let i = 0; i < duplicateRows.length; i++) {
      if (i + 1 < duplicateRows.length) {
        if (duplicateRows[i].data[0] !== duplicateRows[i + 1].data[0]) {
          noDuplicates.push(duplicateRows[i]);
        }
      }

The issue with this code is the duplicates are still being returned in the noDuplicates array

2 Answers 2

1

The problem with your code is that it's only comparing the current object to the next object. A duplicate of the current object could lie anywhere in the array, and your code does not take that into account.

Use this instead:

let firstElements = [];
let noDuplicates = [];
duplicateRows.forEach(object => {
    if (!firstElements.includes(object.data[0])) {
        firstElements.push(object.data[0]);
        noDuplicates.push(object);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

A different approach.

Iterate the array, and create an object. Since object keys are unique, it will replace if there is a duplicate. You can also add a check if a key is already there, in that case don't update it again.

let list = [{
    data: ["22409972", "1267304", "1000", "FG-18-1267304"]
  },
  {
    data: ["22409972", "1267304", "2000", "FG-18-1267304"]
  },
  {
    data: ["22409979", "1267304", "2000", "FG-18-1267304"]
  },
  {
    data: ["224099720", "1267304", "2000", "FG-18-1267304"]
  },
  {
    data: ["224099728", "1267304", "2000", "FG-18-1267304"]
  },
  {
    data: ["224099728", "1267304", "2000", "FG-18-1267304"]
  }
];


let result = {};

list.forEach(item => {
  result[item.data[0]] = item;
});

console.log(Object.values(result));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.