-3

I try to look for duplicates in the array and get an error, and I glad for any solution for this problem Attached is code:

let names = itemList[0].getElementsByTagName("span")[0].innerText;
for (i = 1; i < itemList.length; i++) {
  if (!(itemList[i].getElementsByTagName("span")[0].innerText in names)) {
    names.push(itemList[i].getElementsByTagName("span")[0].innerText);
  }
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • Can you fix your code indentation? This improves the readability. Thank. – Reporter Nov 02 '21 at 15:08
  • 2
    Make an empty Set. Check to see if each item is already in the Set; if it is, it's a duplicate. Then add it to the Set. – mykaf Nov 02 '21 at 15:08
  • 3
    Does this answer your question? [Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array](https://stackoverflow.com/questions/840781/get-all-non-unique-values-i-e-duplicate-more-than-one-occurrence-in-an-array) – MuzaffarShaikh Nov 02 '21 at 15:09

1 Answers1

0

You can use indexOf. If the indexOf that item in the array you're trying to push to is -1, that means it doesn't exist, and that you can go ahead and push it in. Otherwise, do nothing. You can also reverse this, and add to the array from the other if it already exists, and do nothing if it doesn't.

Example:

const array = [1, 2, 3, 4, 5, 6, 7, 8];

// We are adding this. Expecting to not add the numbers that are already there
const toPushTo = [1, 10, 5];

const addToArrayIfNotDuplicate = (arr)=> {
  arr.forEach(item=>{
    toPushTo.indexOf(item) === -1 ? toPushTo.push(item) : null;
  })
};

addToArrayIfNotDuplicate(array);
console.log(toPushTo);
mstephen19
  • 1,733
  • 1
  • 5
  • 20