# 数组去重

var arr = ['true','true',true,true,0,0,1,1,15,15,false,false,undefined,undefined,null,null,NaN,NaN,'NaN','NaN','a','a',{},{},{a:2},{a:2}];

# Set()

不考虑兼容性,这种去重的方法代码最少。这种方法还无法去掉“{}”对象,后面的高阶方法会添加去掉重复“{}”的方法。

function unique (arr) {
  return Array.from(new Set(arr))
}
// or
[...new Set(arr)] 

// ["true", true, 0, 1, 15, false, undefined, null, NaN, "NaN", "a", {}, {}, {a:2}, {a:2}]  // {} 没有去重

# Map()

function unique(arr) {
    const newArray = [];
    const tmp = new Map();
    for(let i = 0; i < arr.length; i++){
        if(!tmp.get(arr[i])){
            tmp.set(arr[i], 1);
            newArray.push(arr[i]);
        }
    }
    return newArray;
}

function unique(arr) {
    const tmp = new Map();
    return arr.filter(item => !tmp.has(item) && tmp.set(item, 1) )
}

// ["true", true, 0, 1, 15, false, undefined, null, NaN, NaN, "NaN", "a", {}, {}, {a:2}, {a:2}]  // {} NaN 没有去重

# splice()

双层循环,外层循环元素,内层循环时比较值。值相同时,删除元素,会改变原数组。

function unique(arr){
    for(let i = 0; i < arr.length; i++){
        for(let j = i + 1; j < arr.length; j++){
            if(arr[i] === arr[j]){
                arr.splice(j, 1);
                j--;
            }
        }
    }
    return arr;
}
// ["true", true, 0, 1, 15, false, undefined, null, NaN, NaN, "NaN", "a", {}, {}, {a:2}, {a:2}]  // {} 没有去重

# sort() 相邻比对

利用sort()排序方法,先对原数组进行排序,然后再相邻元素比对

function unique(arr){
    let array = arr.sort();
    let newArr = [];
    for(let i = 0; i < array.length; i++){
        if(array[i] !== array[i + 1]){
            newArr.push(array[i]);
        }
    }
    return newArr;
}
// [0, 1, 15, "NaN", NaN, NaN, {}, {}, {a:2}, {a:2}, "a", false, null, true, "true", undefined]      // NaN、{}没有去重

# indexOf()

// indexOf,返回数组的第一个值,所以使用filter过滤
function unique(arr) {
  return arr.filter((item, index) => arr.indexOf(item) === index);
}

function unique(arr) {
  const newArray = [];
  arr.forEach(item => {
    if (newArray.indexOf(item) === -1) newArray.push(item);
  });
  return newArray;
}

// [0, 1, 15, "NaN", NaN, NaN, {}, {}, {a:2}, {a:2}, "a", false, null, true, "true", undefined]      // NaN、{}没有去重

# forEach + includes完美版(ok)

function unique (arr) {
    let newArr = [];
    let obj = {};
    arr.forEach(item => {
        if (typeof item !== 'object') {
            if (!newArr.includes(item)) {
                newArr.push(item)
            }
        } else {
            // 对象
            let str = JSON.stringify(item)
            if (!obj[str]) {
                newArr.push(item)
                obj[str] = 1
            }
        }
    })
    return newArr
}
// [0, 1, 15, "NaN", NaN, NaN, {}, {a:2}, "a", false, null, true, "true", undefined]