1

I have an array, and I want to check if any of the elements in the array are duplicated.

["item1", "item2", "item3"] //false All the items are unique
["item1", "item2", "item1"] //true There are 2 of the same items.
Magical Cat
  • 78
  • 1
  • 7

3 Answers3

2

A simple way is to use a Set.

function doesContainDups(array) {
   let set = new Set(array);
   return set.size !== array.length;
}

console.log(doesContainDups(["item1", "item2", "item3"]));
console.log(doesContainDups(["item1", "item2", "item1"]));
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

If the array is filled with only strings, you can use a set. Create a set from the array, then compare the array length to the set size. If they are the same, then they are unique. If they are different, there is a a duplicate. Here is a simple example.

const arr1 = ["item1", "item2", "item3"];
const arr2 = ["item1", "item2", "item1"];
const setFromArr1 = new Set(arr1);
const setFromArr2 = new Set(arr2);
const arr1AllUnique = arr1.length === setFromArr1.size;
const arr2AllUnique = arr2.length === setFromArr2.size;
console.log(arr1AllUnique);
console.log(arr2AllUnique);
Ben Bradshaw
  • 334
  • 1
  • 6
0

Here's a simple way to test if an array includes duplicates of a specific item.

Usage: containsDuplicateOf(yourArray, "item1")

function containsDuplicateOf(array, item) {
   for (let i = 0; i < array.length; i++) {
       const current = array[i];
       let count = 0;
       for (let j = 0; j < array.length; j++) {
           if (array[j] === current)
               count++;
               
           if (count > 1) return true;
       }
   }

   return false;
}
Haytam
  • 4,643
  • 2
  • 20
  • 43