1. 双层循环
const unique = array => { const res = []; for (let i = 0; i < array.length; i++) { const arrValue = array[i]; for (var j = 0; j < res.length; j++) { const resValue = res[j]; if (arrValue === resValue) { break; } } if (j === res.length) { res.push(arrValue) } } return res;}
2.indexOf
const unique = array => { const res = []; for (let i = 0, len = array.length; i < len; i++) { const current = array[i]; if (res.indexOf(current) === -1) { res.push(current) } } return res;}
3.filter
const unique = array => array.filter((item, index, array) => array.indexOf(item) === index)
4.Object健值对
const unique = array => { const obj = {}; return array.filter(function(item, index, array){ return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true) })}const array = [{value: 1}, {value: 1}, {value: 2}, 2, 1, "1", "2", null, null, undefined, undefined, NaN, NaN];// [ { value: 1 }, { value: 2 }, 2, 1, '1', '2', null, undefined, NaN ]console.log(unique(array));
5.Set
const unique = array => [...new Set(array)];
6.Map
const unique = array => { const map = new Map(); return array.filter(a => !map.has(a) && map.set(a, 1));};