Home >Web Front-end >JS Tutorial >How Can I Remove Duplicate Values from a JavaScript Array?

How Can I Remove Duplicate Values from a JavaScript Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 12:22:11989browse

How Can I Remove Duplicate Values from a JavaScript Array?

Remove Duplicate Values from JS Array

Duplicating elements in JavaScript arrays is a common issue. To address this, various methods can be employed.

Set and Spread Syntax:

The most concise solution utilizes the Set constructor and the spread syntax:

uniq = [...new Set(array)];

Naïve Approach:

For simplicity, a straightforward approach involves filtering elements based on their index:

uniqueArray = a.filter(function(item, pos) {
    return a.indexOf(item) == pos;
});

Using Hashtables:

A more efficient method leverages hashtables, using object properties as keys:

function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}

Combining Approaches:

To handle diverse arrays, a hybrid solution combines hashtables for primitives and linear search for objects:

function uniq(a) {
    var prims = {"boolean":{}, "number":{}, "string":{}}, objs = [];

    return a.filter(function(item) {
        var type = typeof item;
        if(type in prims)
            return prims[type].hasOwnProperty(item) ? false : (prims[type][item] = true);
        else
            return objs.indexOf(item) >= 0 ? false : objs.push(item);
    });
}

Sorting and Filtering:

Sorting before filtering provides another option, removing duplicates based on adjacent elements:

function uniq(a) {
    return a.sort().filter(function(item, pos, ary) {
        return !pos || item != ary[pos - 1];
    });
}

Custom Comparison:

For unique comparisons, a callback can be passed, with equal "keys" being filtered:

function uniqBy(a, key) {
    var seen = {};
    return a.filter(function(item) {
        var k = key(item);
        return seen.hasOwnProperty(k) ? false : (seen[k] = true);
    })
}

The above is the detailed content of How Can I Remove Duplicate Values from a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn