Many times we need to determine the presence of duplicate or repeated elements in a javascript array such as when applying a duplicate validation over a field on a page.
There are many ways to check for elements of same value in a javascript array and this article will outline a few of those.

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.
With this concept, we can easily find out if an array contains duplicate values using below steps.

  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.

Checking for the entry should be done before adding otherwise, it will mark the array duplicate for the very first element.
Javascript code for this approach is given below.

   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) {
         document.write('Array contains duplicate elements');
      } else {
         document.write('Array does not contain duplicate elements');
      }
   }

Note that here 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.

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) {
         document.write('Array contains duplicate elements');
      } else {
         document.write('Array does not contain duplicate elements');
      }
   }

For calculating the size of array, use its length property and for getting the size of a Set object, use its size property.
Set creating and comparison of its size with array length can also be performed in one-liner as

if(arr.length !== new Set(arr).size) {
   result = true;
}

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) {
         document.write('Array contains duplicate elements');
      } else {
         document.write('Array does not contain duplicate elements');
      }
   }

Note that for getting the first index of an element use indexOf function with the element as argument and to get its last index, use lastIndexOf function.
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();

   // callback function
   function checkIndex(element, index) {
      // compare the index of array element with the supplied index
      return arr.indexOf(element) !== index
   }
   function checkDuplicate() {
      let arr = ["abc","xy","bb", "abc"];
      let result = false;
      // call some function with callback function as argument
      result = arr.some(checkIndex);
      if(result) {
         document.write('Array contains duplicate elements');
      } else {
         document.write('Array does not contain duplicate elements');
      }
   }

With ES6, It is also possible to supply a javascript arrow function as an argument to show. This eliminates the need to define it as a separate function and makes the code more cleaner.
Thus, show with an arrow function as argument may be modified as

result = arr.some((element, index) => {return arr.indexOf(element) !== index});

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) {
         document.write('Array contains duplicate elements');
      } else {
         document.write('Array does not contain duplicate elements');
      }
   }

Hit the clap button below if the article was useful.

1 Comment

  1. Number 5 only compared the first element with the rest and returns true if it just happens to match. If you change it so that the first element doesn’t match with anything, then this code gives an error.

Leave a Reply