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))}
js 去重
原文地址:https://www.cnblogs.com/flxy-1028/p/10231136.html