方式一:使用filter()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
// item:当前项,index:当前索引,arr:当前数组
arr1.filter((item, index, arr) => {
if (arr.indexOf(item) === index) {
arr2.push(item)
}
})
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
方式二:使用includes()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
arr1.forEach(item => {
if (!arr2.includes(item)) {
arr2.push(item)
}
})
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
方式三:使用indexOf()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
arr1.forEach(item => {
if (arr2.indexOf(item) < 0) {
arr2.push(item)
}
})
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]
方式四:使用es6
的Set()
let arr1 = [1, 4, 4, 3, 1, 2, 5, 5, 9, 1]
let arr2 = []
// Set()去自动去除重复项
arr2 = [...new Set(arr1)]
console.log(arr2); //[ 1, 4, 3, 2, 5, 9 ]