loading...

Find duplicate or repeat elements in js array

huyddo profile image Huy Dohttps://dev.to/new ・5 min read

There are a couple of ways to count duplicate elements in a javascript array. by using the forEach or for loop.

Declare empty object
Iterate over the array using a for loop.
Using an array element as the key
Increment value of the key if it's presented or initialize the key to 1

const a = [4,3,6,3,4,3]

function count_duplicate(a){
 let counts = {}

 for(let i =0; i < a.length; i++){ 
     if (counts[a[i]]){
     counts[a[i]] += 1
     } else {
     counts[a[i]] = 1
     }
    }  
    for (let prop in counts){
        if (counts[prop] >= 2){
            console.log(prop + " counted: " + counts[prop] + " times.")
        }
    }
  console.log(counts)
}

count_duplicate(a)
/*  3 counted: 3 times.
    4 counted: 2 times.
    { '3': 3, '4': 2, '6': 1 }
*/
const items2 = ['pencil', 'book','pencil']

function find_duplicate_in_array(array){
const count = {}
const result = []

array.forEach(item => {
    if (count[item]) {
       count[item] +=1
       return
    }
    count[item] = 1
})

for (let prop in count){
    if (count[prop] >=2){
        result.push(prop)
    }
}

console.log(count)
return result;

}

find_duplicate_in_array(items2)
// {pencil: 2, book: 1}
//[pencil

Here are few methods to check the duplicate value in javascript array.

Method 1. Using an object

A javascript object consists of key-value pairs where keys are unique. If you try to add a duplicate key with a different value, then the older value for that key is overwritten by the new value.

  1. Declare an empty object.
  2. Iterate over the array using a for loop.
  3. In every iteration, add a new entry in the object created in step 1 with the array element as key and with some fixed value.
  4. Check for the presence of an entry in the object with the current array element as the key.
  5. If an entry is already there, means that the array had another element with the same value and terminate the loop.
checkDuplicate();
   function checkDuplicate() {
      let arr = ["abc","xy","bb", "axz", "abc"];
      // empty object
      let map = {};
      let result = false;
      for(let i = 0; i < arr.length; i++) {
         // check if object contains entry with this element as key
         if(map[arr[i]]) {
            result = true;
            // terminate the loop
            break;
         }
         // add entry in object with the element as key
         map[arr[i]] = true;
      }
      if(result) {
         console.log('Array contains duplicate elements');
      } else {
         console.log('Array does not contain duplicate elements');
      }
   }

Checking for the entry should be done before adding otherwise, it will mark the array duplicate for the very first element.

We are adding a boolean true as the value of object entry, but you can add any other value. In that case, the comparison should also be done with the same value that was added.

You can use document.write for Chrome Dev or console.log as well. I use console.log just for testing purposes.

Method 2. Using a Set

With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor.
If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements. Note that the original array will not be modified.
If we compare the length of original array and the Set object created using this array and there is a mismatch, this clearly means that the array had at least one duplicate item.
Javascript code for this method is given below.

   checkDuplicate();

   function checkDuplicate() {
      let arr = ["abc","xy","bb", "abc"];
      let result = false;
      // create a Set with array elements
      const s = new Set(arr);
      // compare the size of array and Set
      if(arr.length !== s.size){
         result = true;
      }
      if(result) {
         console.log('Array contains duplicate elements');
      } else {
         console.log('Array does not contain duplicate elements');
      }
   }

Method 3. Comparing the indexes of element

This method works on comparing two indexes of array element, one is the first index and other is the last index.
If they both are same, means the element occurs only once in the array but if they are different, it clearly means that the element occurs more than once as the same element can not have 2 different indexes.
This approach requires iterating over the array using a for loop but only till the first and last index of an element match. At this point the loop should be terminated.
Javascript code for this method is given below.

checkDuplicate();
   function checkDuplicate(){
      let arr = ["abc","xy","bb", "abc"];
      let result = false;
      // iterate over the array
      for(let i = 0; i < arr.length;i++) {
         // compare the first and last index of an element
         if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])){
            result = true;
            // terminate the loop
            break;
         }
      }
      if(result) {
         console.log('Array contains duplicate elements');
      } else {
         console.log('Array does not contain duplicate elements');
      }
   }

Method 4. Using some function

Javascript some function checks all the elements of an array for a condition and returns true if any of the elements satisfy that condition.
The condition to be checked is supplied as an argument function to some. This function is a callback function, it is called for every array element one by one and should return either true or false.
It is called till it returns false, once it returns true, it is not called.
The argument function accepts three arguments,

  • value: Value of current array element.
  • index: Index of supplied array element.
  • array: The array itself.

Logic

In the argument callback function, we get the current array element as the first argument and the index of current element as the second argument.
Now, we get the first index of the array element using indexOf function and compare it with the index supplied as the second argument.
If the indexes match, means the array element occurs only once. If the indexes do not match, the element is considered to be occurring more
Javascript program to check duplicate array element using some function is given below.

checkDuplicate();
  function checkDuplicate() {
      let arr = ["abc","xy","bb", "abc"];
      let result = false;
      // call some function with callback function as argument
      result = arr.some((element, index) => {return arr.indexOf(element) !== index});
      if(result) {
         console.log('Array contains duplicate elements');
      } else {
         console.log('Array does not contain duplicate elements');
      }
   }

Method 5. Using iteration

Compare each element of the array with all other elements to test if it matches with any other element. If a match is found, means that the array contains duplicate elements.
This approach requires a nested loop in which outer loop will iterate over the array elements and inner loop will compare each element with the remaining elements.
Terminate both the loops as soon as a match is found.
Javascript code for this method follows.

checkDuplicate();
   function checkDuplicate(element, index) {
      let arr = ["abc","xy","bb", "abc"];
      for(let i = 0; i < arr.length;i++) {
         // nested loop
         for(let j = 0; j < arr.length;j++) {
            // do not compare same elements
            if(i !== j) {
              // check if elements match
        if(arr[i] === arr[j]){
                 // duplicate element found
           result = true;
                 // terminate inner loop
           break;
        }
            }
         }
         // terminate outer loop
         if(result){
            break;
         }
      }
      if(result) {
         console.log('Array contains duplicate elements');
      } else {
         console.log('Array does not contain duplicate elements');
      }
   }

References
https://codippa.com/how-to-check-if-array-contains-duplicate-values-in-javascript/

Posted on by:

huyddo profile

Huy Dohttps://dev.to/new

@huyddo

Full Stack SE. I love to build beautiful web apps and learn new technologies.

Discussion

markdown guide