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
Release: 2024-12-22 12:22:11
Original
942 people have browsed it

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)];
Copy after login

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;
});
Copy after login

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);
    });
}
Copy after login

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);
    });
}
Copy after login

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];
    });
}
Copy after login

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);
    })
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template