乐趣区

关于javascript:数组去重

for 循环?NONONO

ES678 来袭

先来一个数组

  var baseArray = [1, 1, '1', '1', null, null,
    undefined, undefined,
    new String('1'), new String('1'),
    /a/, /a/,
    NaN, NaN
  ];

set

  let unique_1 = arr => [...new Set(arr)];
  // let unique_1 = arr => Array.from(new Set(arr))
  console.log(unique_1(baseArray));

输入

[1, "1", null, undefined, String, String, /a/, /a/, NaN]

filter

 let unique_2 = arr => {let res = arr.filter((item, index, array) => {return array.indexOf(item) === index; // 以后元素在数组中第一次呈现则返回 true
    })
    return res;
  }
  console.log(unique_2(baseArray));

输入

[1, "1", null, undefined, String, String, /a/, /a/]

这个把 NaN 过滤了,因为 Array.indexOf(NaN) 值为 -1

reduce

  let unique_3 = arr => arr.reduce((pre, cur) => pre.includes(cur) ? pre : [...pre, cur], []);
  console.log(unique_3(baseArray));

输入

[1, "1", null, undefined, String, String, /a/, /a/, NaN]

原理跟一般 for 循环雷同,先申明一个空数组,如果 includesfalse,则 push 以后元素,只不过逼格高那么一丢丢丢丢

键值对

  let unique_4 = arr => {let obj = {};
    return  arr.filter(item => Reflect.has(obj, typeof item + item) ? false : (obj[typeof item + item] = true));
  }
  console.log(unique_4(baseArray))

输入

[1, "1", null, undefined, String, /a/, NaN]

从某种意义上来说,这个办法最完满

obj[typeof item + item]写法原因:对象的 key 必须是字符串

退出移动版