关于JavaScript 数组去重方法
遍历法
const foo = () => {
for (i=0; i<arr.length; i++) {
let k = 1
for (j=i+1; j<arr.length; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1)
j--
k++
}
}
console.log(`The number of the ${arr[i]} is ${k}`)
}
}
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log(arr)
foo(arr)
console.log(arr)
/**
[
1, 1, 1, 11, 22, 33,
33, 33, 555, 77, 88, 88,
88
]
The number of the 1 is 3
The number of the 11 is 1
The number of the 22 is 1
The number of the 33 is 3
The number of the 555 is 1
The number of the 77 is 1
The number of the 88 is 3
[
1, 11, 22, 33,
555, 77, 88
]
*/
forEach 方法,此方法如果在数组里不存在将push到新数组
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
const foo = (data) => {
let newArr = []
data.forEach(element => {
if (!newArr.includes(element)){
newArr.push(element)
}
})
return newArr
}
console.log(foo(arr))
[
1, 1, 1, 11, 22, 33,
33, 33, 555, 77, 88, 88,
88
]
[
1, 11, 22, 33,
555, 77, 88
]
filter 方法, 此方法将依据条件创造一个新的数组,并且没有在filtered 数组里将返回false
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
const foo = (data) => {
return data.filter((value, index)=>
data.indexOf(value) === index
)
}
console.log(foo(arr))
[
1, 11, 22, 33,
555, 77, 88
]
reduce方法,此方法将减少数组里面的元素并且依据你提供的reducer函数合并到一个最终的数组
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
const foo = (data) => {
let newArr = data.reduce((prev, next) => {
if (prev.indexOf(next) < 0) {
prev.push(next)
}
return prev
}, [])
return newArr
}
console.log(foo(arr))
// or
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
const foo = (data) => {
return data.reduce((prev, curr) =>
prev.includes(curr) ? prev : [...prev, curr], []);
}
console.log(foo(arr))
[
1, 11, 22, 33,
555, 77, 88
]
添加 unique 方法到 Array Prototype, 利用数组 prototype 构造函数添加新的属性和方法到一个 Array 对象
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
Array.prototype.unique = function() {
let newArr = []
for (let i=0; i<this.length; i++){
let curr = this[i]
if (newArr.indexOf(curr) < 0) newArr.push(curr)
}
return newArr
}
console.log(arr.unique())
// Or
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
Array.prototype.unique = function() {
return Array.from(new Set(this));
}
console.log(arr.unique())
[
1, 11, 22, 33,
555, 77, 88
]
使用 Set, 创造一个unique values 集合
let arr = [1,1,1,11,22,33,33,33,555,77,88,88,88]
console.log (arr)
const foo = (data) => {
return [...new Set(data)]
}
console.log(foo(arr))
[
1, 11, 22, 33,
555, 77, 88
]