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!