How to check if array has duplicates values - JS

Mo Ibra

Mo Ibra

Dec 26, 2022

In this article we will learn how to check if checkbox is checked or not.

It is very common to check if checkbox is checked or not in JavaScript.


Problem

Now we have a problem, which is that we want to know if the array contains duplicates elements or not.

Let's imagine we have a array like this:

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

As you see ! There is more than one duplicate element in that array, and we only want to:

  • return true if it contains duplicate elements.
  • return false if it does not contain duplicate elements.

How to solve this problem?

Well, there is more than one solution to this problem, and they are all correct:

  • Using forEach
  • Using new Set()

In this article we will try to explain them in detail together, clarifying the differences between them.

Check if array has duplicates elements using forEach

We can use forEach to itreate over elements and check if array has duplicates or not.

Example

// Our array
const array = [1, 2, 3, 3, 4, 5, 6, 1, -1, 6];

// Unique elements
const unique = [];

// Duplicates elements
const duplicates = [];

// Iterate and check for duplicates elements
array.forEach(ele => {
    if (unique.includes(ele)) {
        duplicates.push(ele);
    } else {
        unique.push(ele);
    }
});

// Print uniqu
console.log(unique);

// Print duplicates
console.log(duplicates);

Output

[
  1, 2,  3, 4,
  5, 6, -1    
]
[ 3, 1, 6 ]

As you can see, we have separated the elements into two arrays, the first array contains the unique elements and the second contains the duplicate elements.

Now you can easily create a function that returns true or false

function hasDuplicates(arr) {

    // Unique elements
    const unique = [];

    // Duplicates elements
    const duplicates = [];
    
    // Iterate and check for duplicates elements
    arr.forEach(ele => {
        if (unique.includes(ele)) {
            duplicates.push(ele);
        } else {
            unique.push(ele);
        }
    });
    
    // If has duplicates return true
    if (duplicates.length > 1) return true;

    // Otherwise return false
    return false;
}

const array = [1, 2, 3, 3, 4, 5, 6, 7, 7];
console.log(hasDuplicates(array));

Check if array has duplicates elements using set

We can check if an array has duplicates using new Set(arr).

Example

function hasDuplicates(arr) {

    const set = new Set(arr);

    if (arr.length === set.size) {
        return false
    } else {
        return true;
    }
}

const array1 = [1, 2, 3, 3, 4, 5, 6, 7, 7];
const array2 = [1, 2, 3];

console.log(hasDuplicates(array1));
console.log(hasDuplicates(array2))

Output

true
false

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: