Array deduplicating encountered in real projects is generally handled by the background, rarely let the front end deal with array deduplicating. Although the probability of daily projects is relatively low, but still need to know, in case the interview may be asked back.

A method to remove the weight of an array

ES6 Set (most commonly used in ES6)

New Set cannot determine NaN, null, undefined, {} data types and cannot remove {}

Function unique (arr) {return Array. The from (new Set (arr)]} var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)) //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]Copy the code

Regardless of compatibility, this method of de-duplication has the least code. This method also does not remove the empty ‘{}’ object; later higher-order methods add methods to remove the duplicate ‘{}’ object.

2, use for to nest for, and then splice (ES5 most commonly used)

== does not recognize two NaN and {} comparisons as always being unequal

function unique(arr){ for(var i=0; i<arr.length; i++){ for(var j=i+1; j<arr.length; J ++){if(arr[I]==arr[j]){if(arr[I]==arr[j]){ j--; } } } return arr; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; Console. log(unique(arr)) //[1, "true", 15, false, undefined, NaN, NaN, "NaN", "a", {...}, {...}] //NaN and {} are nullCopy the code

Double loop, outer loop element, outer element subscript position begins to compare with the inner loop value. If the values are the same, delete this value.

3. Use indexOf to remove weight

IndexOf cannot remove elements like NaN and {}

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return } var array = []; for (var i = 0; i < arr.length; i++) { if (array .indexOf(arr[i]) === -1) { array .push(arr[i]) } } return array; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; Console. log(arr) // [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN", 0, "a", {...}, {...}] //NaN, {} are not de-weightedCopy the code

Create an empty result array, loop through the original array, check whether the result array has the current element, skip if they have the same value, push into the array if they do not.

Sort ()

! == is unable to determine NaN and {}, and is considered to always want to wait

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return; } arr = arr.sort() var arrry= [arr[0]]; for (var i = 1; i < arr.length; i++) { if (arr[i] ! == arr[i-1]) { arrry.push(arr[i]); } } return arrry; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [0, 1, 15, "NaN," NaN, NaN, {...}, {...}, "a", false, null, true, "true", Undefined] //NaN, {Copy the code

Use sort() sorting method, and then traverse and compare adjacent elements according to the sorted result.

5, the use of object attributes can not be the same characteristics for deduplication (this array deduplication method has problems, not recommended, need to be improved)

Convert each item in the array to an object property, assign a value to it, and then remove or remove it based on whether it has a value. True is not an object property, NaN and {} are

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return } var arrry= []; var obj = {}; for (var i = 0; i < arr.length; i++) { if (! obj[arr[i]]) { arrry.push(arr[i]) obj[arr[i]] = 1 } else { obj[arr[i]]++ } } return arrry; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; Console. log(unique(arr)) //[1, "true", 15, false, undefined, null, NaN, 0, "a", {...}Copy the code

Vi. Use includes

{} includes includes, undefined, null, NaN, etc. {}

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return } var array =[]; for(var i = 0; i < arr.length; i++) { if( ! Array.push (arr[I]); array.push(arr[I]); }} return array} var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [1, "true", true, 15, false, undefined, null, NaN, "NaN," 0, "a", {...}, {...}] / / {} not to heavyCopy the code

Use hasOwnProperty

function unique(arr) { var obj = {}; return arr.filter(function(item, index, arr){ return obj.hasOwnProperty(typeof item + item) ? false : (obj [typeof item + item] = true)})} var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined. null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)) //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {...}] // Use hasOwnProperty to check if object attributes existCopy the code

8. Use filter

Arr. Filter (function(item, index, arr) {return arr. Filter (function(item, index, arr) {return arr. Return arr.indexof (item, 0) === index; }); } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [1, "true", true, 15, false, undefined, null, "NaN," 0, "a", {...}, {...}]Copy the code

Use recursion to duplicate

=== is always considered unequal for both Nans and {}

function unique(arr) {
        var array= arr;
        var len = array.length;

    array.sort(function(a,b){   //排序后更加方便去重
        return a - b;
    })

    function loop(index){
        if(index >= 1){
            if(array[index] === array[index-1]){
                array.splice(index,1);
            }
            loop(index - 1);    //递归loop,然后数组去重
        }
    }
    loop(len-1);
    return array;
}
 var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
console.log(unique(arr))
//[1, "true", true, 15, false, 1, {…}, null, NaN, NaN, "NaN", 0, "a", {…}, undefined]
Copy the code

10. Use Map data structure to remove weight

A new Map is just like an object, adding a set of attributes,

function arrayNonRepeatfy(arr) { let map = new Map(); let array = new Array(); For (let I = 0; i < arr.length; I++) {if (map) from the (arr) [I]) {/ / if you have the key value map. The set (arr [I], true); } else { map .set(arr[i], false); Array.push (arr[I]); } } return array ; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [1, "a", "true", true, 15, false, 1, {...}, null, NaN, NaN, "NaN," 0, "a", {...}. Undefined] creates an empty Map data structure that iterates through the array to be de-duplicated, storing each element of the array as a key in the Map. Since the Map does not have the same key value, the final result is the result after the deduplication.Copy the code

11. Use reduce+includes

function unique(arr){ return arr.reduce((prev,cur) => prev.includes(cur) ? prev : [...prev,cur],[]); } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)); / / (1, "true", true, 15, false, undefined, null, NaN, "NaN," 0, "a", {...}, {...}]Copy the code

12, […new Set(arr)]

[...new Set(arr)] ---- [...new Set(arr)] [...new Set(arr)] ----Copy the code