Three Methods for Removing Duplicates from Arrays in JavaScript

Using Map Data Structure for Deduplication

A Map object can be employed to track unique values efficiently. The following function iterates through the input array, using a Map to check for duplicates and building a result array with only unique elements.

function removeDuplicatesWithMap(inputArray) {
    const valueMap = new Map();
    const uniqueValues = [];
    
    for (const element of inputArray) {
        if (!valueMap.has(element)) {
            valueMap.set(element, true);
            uniqueValues.push(element);
        }
    }
    
    return uniqueValues;
}

const sampleData = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5];
console.log(removeDuplicatesWithMap(sampleData)); // Output: [1, 2, 3, 4, 5]

Simplifying Deduplication with ES6 Set

The Set object stores unique values of any type. By converting an array to a Set and back, duplicates are automatically removed.

const duplicateArray = [1, 2, 3, 4, 5, 5, 4, 3];
const uniqueArray = [...new Set(duplicateArray)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

Deduplication Using forEach and indexOf

Thiss approach uses forEach to iterate and indexOf to check for later occurrences of each element, collecting only those with out duplicates ahead.

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

function getUniqueElements(arr) {
    const output = [];
    
    arr.forEach((currentValue, currentIndex, array) => {
        const duplicateIndex = array.indexOf(currentValue, currentIndex + 1);
        if (duplicateIndex === -1) {
            output.push(currentValue);
        }
    });
    
    return output;
}

const result = getUniqueElements(originalArray);
console.log(result); // Output: [1, 2, 3, 4, 5]

Tags: javascript array deduplication ES6 programming

Posted on Mon, 26 Oct 2026 16:48:45 +0000 by boinnk