A method to remove the weight of an array

Preface: Two ideas

  1. Two layer cycle method

  2. Take advantage of syntax’s own key unrepeatability

    Both are essentially apis in different languages, not separate methods, such as the indexOf and includes layer loops are of the same class

ES6 Set (most commonly used in ES6)

function unique (arr) {
  return Array.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]){         // The first is the same as the second, and the splice method deletes the second
                    arr.splice(j,1); 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 {} not to heavy, two null directly disappeared
Copy the code

Double loop, outer loop elements, inner loop when comparing values. If the values are the same, delete this value.

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(unique(arr))
   / / (1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN," 0, "a", {...}, {...}] / / NaN, {} not to heavy
Copy 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', {}, {}];console.log(unique(arr))
/ / [0, 1, 15, "NaN," NaN, NaN, {...}, {...}, "a", false, null, true, "true", undefined] / / NaN, {} not to heavy
Copy the code

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

5. 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.includes( arr[i]) ) {//includes checks whether the array has a valuearray.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(unique(arr))
    / / (1, "true", true, 15, false, undefined, null, NaN, "NaN," 0, "a", {...}, {...}] / / {} not to heavy
Copy 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", {...}] / / all the go
Copy the code

Use hasOwnProperty to determine whether an object property exists

7. Use filter

function unique(arr) {
  return arr.filter(function(item, index, arr) {
    // Current element, the first index in the original array == current index value, otherwise return current element
    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', {}, {}];console.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){   // It is more convenient to remove the weight after sorting
        return a - b;
    })

    function loop(index){
        if(index >= 1) {if(array[index] === array[index-1]){
                array.splice(index,1);
            }
            loop(index - 1);    // loop recursively, then the array is deduplicated
        }
    }
    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

9. Use Map data structure to remove weight

function arrayNonRepeatfy(arr) {
  let map = new Map(a);let array = new Array(a);// The array is used to return the result
  for (let i = 0; i < arr.length; i++) {
    if(map .has(arr[i])) {  // If there is a key value
      map .set(arr[i], true); 
    } else { 
      map .set(arr[i], false);   // If there is no key valuearray .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(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.

X. 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

11, […new Set(arr)]

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

This ES6 approach is highly recommended