Js数组去重的方法
1、ES6 Set方法去重
let arr = [1,2,3,25,4,1,2,3]
function deduplicationBySet(array) {
return [...new Set(arr)]
}
console.log(deduplicationBySet(arr))
2、双重for循环去重
let arr = [1,2,3,25,4,1,2,3]
function deduplicationByFor(array) {
let len = array.length
for (let i = 0; i<len; i++){
for (let j = i+1;j<len; j++){
if (arr[i] === arr[j]) {
arr.splice(j,1)
j--
len--
}
}
}
return array
}
console.log(deduplicationByFor(arr))
3、indexOf实现去重
let arr = [1,2,3,25,4,1,2,3]
function deduplicationByIndexOf(array) {
let arr = []
for (let i = 0; i<array.length; i++) {
if (arr.indexOf(array[i]) === -1){
arr.push(array[i])
}
}
return arr
}
console.log(deduplicationByIndexOf(arr))
4、includes实现去重
let arr = [1,2,3,25,4,1,2,3]
function deduplicationByIncludes(array) {
let arr = []
for (let i = 0; i<array.length; i++) {
if (!arr.includes(array[i])){
arr.push(array[i])
}
}
return arr
}
console.log(deduplicationByIncludes(arr))
5、Filter实现去重
let arr = [1,2,3,25,4,1,2,3]
function deduplicationByFilter(array) {
return array.filter((item,index) => {
return array.indexOf(item,0) === index
})
}
console.log(deduplicationByFilter(arr))