1、使用 Set
let arr = [1, 3, 3, 4, 4, 4, 4, true, true, false, false]
let res = [...new Set(arr)]
console.log(res)
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let res = [...new Set(arr)]
console.log(res)
2、for 循环 + splice
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let len = arr.length
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
if (arr[j] === arr[i]) {
arr.splice(j, 1)
len--
j--
}
}
}
console.log(arr)
3、使用 indexOf
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let res = []
for (let i = 0; i < arr.length; i++) {
if(res.indexOf(arr[i]) === -1) res.push(arr[i])
}
console.log(res)
4、使用 includes
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let res = []
for (let i = 0; i < arr.length; i++) {
if(!res.includes(arr[i])) res.push(arr[i])
}
console.log(res)
5、使用 find,findIndex
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let res = []
for (let i = 0; i < arr.length; i++) {
let findItem = res.find(item=>item === arr[i])
if(!findItem) res.push(arr[i])
}
console.log(res)
6、使用 filter
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let res = arr.filter((item, index) => arr.indexOf(item) === index)
console.log(res)
7、使用 map
let arr = [1, 3, 3, 4, 4, { a: 1, b: 2 }, { a: 1, b: 2 }]
let map = new Map()
let res = []
for (let i = 0; i < arr.length; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], true)
res.push(arr[i])
}
}
console.log(res)