Array to heavy, is generally in the interview will encounter, is generally required to handwritten array to heavy method of code. If you are asked, what are the methods of array de-duplication? If you can answer 10 of these questions, there’s a good chance you’ll impress your interviewer.

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.

Note: I am writing in a hurry, and I have been a little busy these days, so I haven’t checked it carefully. However, there is no problem in my thinking, and some small details may be wrong.

A method to remove the weight of an array

ES6 Set (most commonly used in ES6)

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)

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 elements, inner loop when comparing values. If the values are the same, delete this value. For a quick look at more common ES6 syntax, check out my previous post

3. Use indexOf to remove weight

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 ()

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)

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

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", {...}Copy the code

Use hasOwnProperty to determine whether an object property exists

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

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, "a", "true", true, 15, false, 1, {…}, null, NaN, NaN, "NaN", 0, "a", {…}, undefined]
Copy the code

10. Use Map data structure to remove weight

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]Copy the code

Create an empty Map data structure that iterates through the array to be repealed, 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.

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)] ----Copy the code

The article reprinted quietly flashes