EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

关于数组去重 #12

Open EdwardZZZ opened 7 years ago

EdwardZZZ commented 7 years ago

let arr = [1, 2, 3, 4, 5, 4, 3, 11]; let newArr;

ES6
// Array.from 耗时是 ... 的2.5倍
newArr = [...new Set(arr)]

ES5
arr.forEach((n) => {
    !~newArr.indexOf(n) && newArr.push(n);
})

利用object的key去重
let __tempObj = {};

arr.forEach((n) => {
    __tempObj[n] = n
})

Object.keys(__tempObj)

用方法去测速 Array.apply(null, {length: 100000}).forEach(() => { // CODE })

得出结论ES5的速度最快,其中第三种方法如果只是用检测是否存在 (替代es5中的indexOf) ,然后再push的方法速度快60%

arr.forEach((n) => {
    if(!__tempObj[n]){
        __tempObj[n] = n;
        newArr.push(n);
    }
})