Wednesday, September 25, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Find Duplicate Elements in an Array

JavaScript Program to Find Duplicate Elements in an Array

In this article, we are going to understand how we can find elements in an array whose frequency is greater than one. Finding duplicate elements in an array means identifying and listing any values that appear more than once within the array, helping to detect and manage redundant data or repeated elements within a collection of items.

There are several methods that can be used to find duplicate elements in an array by using JavaScript, which are listed below:

  • Using Nested For In-Loop
  • Using Sort() method
  • Using filter() method
  • Using a Single Loop and includes() Method
  • Using a Set
  • Using Reduce Method

We will explore all the above methods along with their basic implementation with the help of examples

Approach 1: Using Nested For In Loop

In the loop, we will give each index of the array to iterate, and in each iteration, we are checking that the element at any iteration is the same or not; if they are the same, then we add it to duplicated_elements, and if iterations are the same, then we skip it.

Syntax:

for (let i in obj1) {
// Prints all the keys in
// obj1 on the console
console.log(i);
};

Example: The below code will illustrate the approach.

Javascript




let check_duplicate_in_array = (input_array) => {
    let duplicate_elements = []
    for (num in input_array) {
        for (num2 in input_array) {
            if (num === num2) {
                continue;
            }
            else {
                if (input_array[num] === input_array[num2]) {
                    duplicate_elements.push(input_array[num]);
                }
            }
        }
    }
    return [...new Set(duplicate_elements)];
}
let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6, 1];
console.log(check_duplicate_in_array(arr));


Output

[ 1, 2, 3 ]

Approach 2: Using Sort() Method

This array.sort() method is provided by Javascript by which we can sort our array, and after sorting the array, we are checking that the element at the last index is the same or not; if they are the same, it means it’s a duplicate element.

Syntax:

array.sort();

Example: Below code will illustrate the approach.

Javascript




let check_duplicate_in_array = (input_array) => {
    input_array = input_array.sort((a, b) => a - b);
    let duplicate_elements = []
    for (index in input_array) {
        if (input_array[index] ===
            input_array[index - 1]) {
            duplicate_elements.push(
                input_array[index]);
        }
    }
    return [...new Set(duplicate_elements)];
}
let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6, 1];
console.log(check_duplicate_in_array(arr));


Output

[ 1, 2, 3 ]

 Approach 3: Using filter() Method

The array filter() method returns elements of the array that pass the condition of the array and forms a new array by using these elements, and here we are checking whether a particular element has two different indexes or not; if they do, they are duplicate elements.

Syntax:

array.filter(callback(element, index, arr), thisValue)

Example: Below code will illustrate the approach.

Javascript




const check_duplicate_in_array=(input_array)=>{
    const duplicates =input_array.filter((item, index) =>input_array.indexOf(item) !== index);
    return Array.from(new Set(duplicates));
}
const arr=[1,1,2,2,3,3,4,5,6,1];
console.log(check_duplicate_in_array(arr));


Output

[ 1, 2, 3 ]

Approach 3 : Using a Single Loop

For all loops, it iterates over iterable data structures and gives the element in each iteration, and in each iteration, we are checking that a particular element has another last index or not; if it has another last index, it’s a duplicated element.

Syntax:

for ( variable of iterableObjectName) {
...
};

Example: Below code will illustrate the approach.

Javascript




let check_duplicate_in_array = (input_array) => {
    let duplicate_elements = [];
    for (element of input_array) {
        if (input_array.indexOf(element)
            !== input_array.lastIndexOf(element)) {
            duplicate_elements.push(element);
        }
    }
    return [...new Set(duplicate_elements)];
};
let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6, 1];
console.log(check_duplicate_in_array(arr));


Output

[ 1, 2, 3 ]

Approach 4: Using a Set

A data structure is said to be a set when no elements repeat in it. Here, we are checking whether a particular element exists in the set or not. If it does, it means it’s a duplicated element. If not, we add it to duplicated_element.

Syntax:

new Set([it]);

Example: Below code will illustrate the approach.

Javascript




let check_duplicate_in_array = (input_array) => {
    let unique = new Set();
    let duplicated_element = [];
    for (let i = 0; i < input_array.length; i++) {
        if (unique.has(input_array[i])) {
            duplicated_element.push(input_array[i]);
        }
        unique.add(input_array[i]);
    }
    return Array.from(new Set(duplicated_element));
};
let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6, 1];
console.log(check_duplicate_in_array(arr));


Output

[ 1, 2, 3 ]

Approach 5: Using Reduce Method

In the reduce method, we traverse an array from left to right and store the results in an accumulator. Here, in each iteration, we are checking if the element at the last index is the same or not because the array is sorted. If they are the same, then we add them to the duplicated_elements accumulator.

Syntax:

array.reduce( function(total, currentValue, currentIndex, arr), initialValue )

Example: Below code will illustrate the approach.

Javascript




let check_duplicate_in_array = (input_array) => {
    input_array = input_array.sort((a, b) => a - b);
    return input_array.reduce(
        (duplicated_elements, current_element, current_index) => {
            if (input_array[current_index] ===
                input_array[current_index - 1]) {
                duplicated_elements.push(current_element);
            }
            return Array.from(new Set(duplicated_elements));
        },
        []
    );
};
let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6, 1];
console.log(check_duplicate_in_array(arr));


Output

[ 1, 2, 3 ]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments