Horje
JavaScript Program to Find Duplicate Elements in an Array

We are going to learn how can we Find Duplicate Elements in an Array. 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:

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.

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.

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.

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 4: 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.

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 5: 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.

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 6: 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.

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 ]

Approach 7: Using indexOf() method

In this approach we are hecking if the index of the element is not equal to -1, indicating that the element is found later in the array. If it is a duplicate and has not been added to the duplicates array yet, it adds it to the array. The result is an array containing only the duplicate values.

Example: Below code will illustrate the approach.

JavaScript
let arr = [1, 2, 3, 4, 5, 2, 6, 3, 7, 8, 8];
let duplicates = [];

arr.forEach(function (value, index, array) {
    if (array.indexOf(value, index + 1) !== -1
        && duplicates.indexOf(value) === -1) {
        duplicates.push(value);
    }
});

console.log("Duplicate values:", duplicates);

Output
Duplicate values: [ 2, 3, 8 ]

Approach 8: Using an Object to Track Frequencies

In this approach, we use a JavaScript object to keep track of the frequency of each element in the array. By iterating through the array and updating the count of each element in the object, we can easily identify duplicate elements. This method is efficient and easy to understand.

Example:

JavaScript
function findDuplicatesUsingObject(input_array) {
    let elementCount = {};
    let duplicates = [];

    // Iterate through the array and count each element's frequency
    for (let i = 0; i < input_array.length; i++) {
        let element = input_array[i];
        if (elementCount[element]) {
            elementCount[element]++;
        } else {
            elementCount[element] = 1;
        }
    }

    // Find elements that have a frequency greater than 1
    for (let element in elementCount) {
        if (elementCount[element] > 1) {
            duplicates.push(parseInt(element));
        }
    }

    return duplicates;
}

// Driver code
let arr = [1, 1, 2, 2, 3, 3, 4, 5, 6, 1];
console.log(findDuplicatesUsingObject(arr));

Output
[ 1, 2, 3 ]

Approach 9: Using Map to Track Frequencies

Another approach to find duplicate elements in an array is by using a Map object to keep track of the frequency of each element. This method is similar to using an object but leverages the Map data structure, which can be more efficient and convenient for certain operations.

Example: In this example, we will use a Map to count the occurrences of each element in the array and then identify the elements that appear more than once.

JavaScript
const findDuplicates = (arr) => {
    const elementMap = new Map();
    const duplicates = [];
    arr.forEach((element) => {
        if (elementMap.has(element)) {
            elementMap.set(element, elementMap.get(element) + 1);
        } else {
            elementMap.set(element, 1);
        }
    });
    elementMap.forEach((count, element) => {
        if (count > 1) {
            duplicates.push(element);
        }
    });

    return duplicates;
};

const array = [1, 3, 4, 3, 4, 1, 3, 3, 3, 4];
const duplicateElements = findDuplicates(array);

console.log(duplicateElements); 

Output
[ 1, 3, 4 ]





Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Remove all occurrences of a character in a string using JavaScript Remove all occurrences of a character in a string using JavaScript
JavaScript Program to Determine the Length of an Array JavaScript Program to Determine the Length of an Array
JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
JavaScript Program to Merge two Sorted Arrays into a Single Sorted Array JavaScript Program to Merge two Sorted Arrays into a Single Sorted Array
JavaScript Program to Determine the Frequency of Elements in an Array and Represent it as an Object JavaScript Program to Determine the Frequency of Elements in an Array and Represent it as an Object

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11