数组去重
let arr2 = ['小王', '小王', '小张']
let newArr2 = [...new Set(arr2)]
console.log("TCL: newArr2", newArr2) // TCL: newArr2 (2) ["小王", "小张"]
数组对象去重
1.reduce()方法
let arr = [
{ name: 'wangqiang', age: 25 },
{ name: 'wangqiang1', age: 26 },
{ name: 'wangqiang1', age: 27 },
{ name: 'wangqiang2', age: 28 }
]
let obj = {};
let newArr = arr.reduce((defaultArr, next) => {
obj[next.name] ? "" : obj[next.name] = true && defaultArr.push(next)
return defaultArr
}, [])
//设置defaultArr默认类型为数组,并且初始值为空的数组
console.log("TCL: newArr", newArr)
// TCL: newArr
// [
// { name: 'wangqiang', age: 25 },
// { name: 'wangqiang1', age: 26 },
// { name: 'wangqiang2', age: 28 }
// ]
2.冒泡排序的思想
let arr1 = [
{ name: 'wangqiang', age: 25 },
{ name: 'wangqiang1', age: 26 },
{ name: 'wangqiang1', age: 27 },
{ name: 'wangqiang2', age: 28 }
]
for (let i = 0; i < arr1.length - 1; i++) {
for (let j = i + 1; j < arr1.length; j++) {
if (arr1[j].name === arr1[i].name) {
arr1.splice(j, 1)
}
}
}
console.log("TCL: arr1", arr1)
// TCL: arr1
// [
// { name: 'wangqiang', age: 25 },
// { name: 'wangqiang1', age: 26 },
// { name: 'wangqiang2', age: 28 }
// ]
删除两个数组中name相同的对象
(项目需求 去掉已经选择的选项)
let arr3 = [
{ name: 'wangqiang', age: 25 },
{ name: 'wangqiang1', age: 26 },
{ name: 'wangqiang2', age: 27 },
{ name: 'wangqiang3', age: 28 }
]
let arr3_1 = [
{ name: 'wangqiang2', age: 28 }
]
arr3 = arr3.filter(item => {
let list = arr3_1.map(v => {
return v.name
})
return !list.includes(item.name)
})
console.log("TCL: arr3", arr3)
// TCL: arr3
// [
// { name: 'wangqiang', age: 25 },
// { name: 'wangqiang1', age: 26 },
// { name: 'wangqiang3', age: 28 }
// ]