The Array Unique Function in Javascript – Remove Duplicates in Javascript Array


JS The Array Unique Function in Javascript - Remove Duplicates in Javascript Array javascript programming languages

NodeJs / Javascript

Suppose we have an array and we want to remove the duplicates and return a new array, here is the function:

1
2
3
4
5
6
7
8
9
10
11
Array.prototype.uniq = function () {
    let data = [];
    // convert arguments (special object) to array
    const arr = [].slice.apply(this, arguments, 0);
    for (let x of arr) {
        if (!data.includes(x)) {
            data.push(x);
        }
    }
    return data;
}
Array.prototype.uniq = function () {
    let data = [];
    // convert arguments (special object) to array
    const arr = [].slice.apply(this, arguments, 0);
    for (let x of arr) {
        if (!data.includes(x)) {
            data.push(x);
        }
    }
    return data;
}

The above defines the uniq method for the array. We use the ES6 include to check if an element has appeared in the array or not. Please note that in javascript, NaN !== NaN (Why Javascript is so weird?) so the include method works just fine.

With ES6 support for Set and the triple-dot expansion (to array), the above can be simply re-written as:

1
2
3
Array.prototype.uniq = function () {
    return [...new Set(this)];
}
Array.prototype.uniq = function () {
    return [...new Set(this)];
}

Lets test it:

1
console.log([NaN, NaN, "a", "aa", 1, "1"].uniq());
console.log([NaN, NaN, "a", "aa", 1, "1"].uniq());

The output is: Array(5) [NaN, “a”, “aa”, 1, “1”] – where you can see that 1 and “1” are type-different in Javascript.

How to Remove Duplicates in Javascript using Filter?

You could also use the filter function to remove the duplicates in JS array – a smart way:

1
2
3
4
5
function removeDuplicate(arr) {
    return arr.filter(function(v, idx) {
        return arr.indexOf(v) == idx;
    });
}
function removeDuplicate(arr) {
    return arr.filter(function(v, idx) {
        return arr.indexOf(v) == idx;
    });
}

The idea is to filter out those elements whose index is different than the first appeared element e.g. indexOf.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
333 words
Last Post: Binary Search to Guess Number Game (C++ Coding Exercise)
Next Post: How to Determine the Type of Tree Nodes using SQL?

The Permanent URL is: The Array Unique Function in Javascript – Remove Duplicates in Javascript Array

Leave a Reply