Find duplicates in an array using javaScript

In this article we shall look at the different methods of finding duplicates in an array. Some of these methods only count the number of duplicate elements while the others also tell us which element is repeating and some do both. You can accordingly choose the best one for your use case.

Table of Contents

  • Using the indexOf() method
  • Using the has() method
  • Using an object & key value pairs
  • Using the "some" function
  • Using iteration
  • Other Related Concepts

Using the indexOf() method


In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don’t match, that implies that the element is a duplicate.All such elements are returned in a separate array using the filter() method.

Let us look at the implementation of this using JavaScript

const arry = [1, 2, 1, 3, 4, 3, 5];

const toFindDuplicates = arry => arry.filter((item, index) => arr.indexOf(item) !== index)
const duplicateElementa = tofindDuplicates(arry);
console.log(duplicateElements);

// Output: [1, 3]

Using the has() method

In the above implementation, the output array can have duplicate elements if the elements have occurred more than twice in an array. To avoid this and for us to count the number of elements duplicated, we can make use of the use() method.

function toFindDuplicates(arry) {
    const uniqueElements = new Set(arry);
    const filteredElements = arry.filter(item => {
        if (uniqueElements.has(item)) {
            uniqueElements.delete(item);
        } else {
            return item;
        }
    });

    return [...new Set(uniqueElements)]
}

const arry = [1, 2, 1, 3, 4, 3, 5];
const duplicateElements = toFindDuplicates(arry);
console.log(duplicateElements);

// Output: [1, 3]

The above solution finds and returns the duplicate elements using the has() method. This works more efficiently than the previous method because each value in the Set has to be unique.


Using an object & key-value pairs

In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value. We use this concept to compare the and find the duplicates.

toFindDuplicates();

function toFindDuplicates() {
    let arry = [1, 2, 1, 3, 4, 3, 5];
    let toMap = {};
    let resultToReturn = false;
    for (let i = 0; i < arry.length; i++) {

        if (toMap[arry[i]]) {
            resultToReturn = true;
            // terminate the loop
            break;
        }

        toMap[arr[i]] = true;
    }

    if (resultToReturn) {
        console.log('Duplicate elements exist'
            ');
        }
        else {
            console.log('Duplicates don'
                t exist ');
            }
        }

This can be used when you are concerned which exact elements have duplicates

Using the "some" function

In JavaScript, the “some” function checks for a condition on all the elements of an array and returns true if any of the array elements satisfy that condition.

In the argument callback function, we obtain the current array element as the first argument and the index of current element as the second argument.

We can then compare the current element’s index to the index of the first element with the same value. If both the indices are the same, that implies that there are no duplicate elements.

toFindDuplicates();

function toFindDuplicates() {
    let arry = [1, 2, 1, 3, 4, 3, 5];
    let resultToReturn = false;
    // call some function with callback function as argument
    resultToReturn = arry.some((element, index) => {
        return arry.indexOf(element) !== index
    });
    if (resultToReturn) {
        console.log('Duplicate elements exist'
            ');
        }
        else {
            console.log('Duplicates don'
                t exist ');
            }
        }

Using iteration

In this method, we compare each element of an array with all other elements of the array to check if two elements’ values are the same using nested for loop.

toFindDuplicates();

function toFindDuplicates(element, index) {
    let arry = [1, 2, 1, 3, 4, 3, 5];
    let resultToReturn = false;
    for (let i = 0; i < arry.length; i++) { // nested for loop
        for (let j = 0; j < arry.length; j++) {
            // prevents the element from comparing with itself
            if (i !== j) {
                // check if elements' values are equal
                if (arry[i] === arry[j]) {
                    // duplicate element present                                
                    resultToReturn = true;
                    // terminate inner loop
                    break;
                }
            }
        }
        // terminate outer loop                                                                      
        if (resultToReturn) {
            break;
        }
    }
    f(resultToReturn) {
            console.log('Duplicate elements exist'
                ');
            }
            else {
                console.log('Duplicates don'
                    t exist ');
                }
            }