元素是简单类型的数组(Number, String, null, undefined, Symbol, boolean)
const arr = [3, 1, 1, 2, 5, 9, 3, 0]
使用Set数据结构
//直接使用Set数据结构,结构赋值
const newArr = [...new Set(arr)];
//直接使用Set数据结构,Array.form()
const newArr = Array.from(new Set(arr))
//使用Set数据结构向新数组添加
const set = new Set(arr);
arr.forEach(x => set.add(x));
const newArr = [...set]
//ps:Set也可字符串去重 [...new Set('aabbcc')].join('')
筛选
const newArr = arr => arr.filter((val, index) => arr.indexOf(val) === index)
元素是复杂数据类型(不过一般都去对比每个数据的id)
const arr = [{
name: '小明',
age: 19
},
{
name:'小红',
age: 20
},
{
name: '小明',
age: 19
}]
const newArr = [];
arr.map((val) => {
if(JSON.stringify(newArr).indexOf(JSON.stringify(val)) == -1){
console.log(1)
newArr.push(val)
}
})
console.log(newArr)
网友评论