js 去重

 
 
function unique(array) {
let obj = {};

return array.filter((item, index, array) => {
let newItem = typeof item === 'function' ? item : JSON.stringify(item)
return obj.hasOwnProperty( typeof item + newItem) ? false : (obj[typeof item + newItem] = true)
})
}
 
ES6
 
var array = [1, 2, 1, 1, '1'];

function unique(array) {
   return Array.from(new Set(array));
}

console.log(unique(array)); // [1, 2, "1"]

甚至可以再简化下:

function unique(array) {
    return [...new Set(array)];
}

还可以再简化下:

var unique = (a) => [...new Set(a)]

此外,如果用 Map 的话:

function unique (arr) {
    const seen = new Map()
    return arr.filter((a) => !seen.has(a) && seen.set(a, 1))
}
 
 
posted @ 2019-01-07 00:09  ypm_wbg  阅读(120)  评论(0编辑  收藏  举报