1.reduce方法
var arr = [1, 2, 3, 4, 4, 5, 5]
var sum = arr.reduce(function (prev, cur) {
console.log(prev, cur)
if (prev.indexOf(cur) == -1) {
prev.push(cur)
}
return prev
}, [])
console.log(sum)
2.forEach
var arr = [1, 2, 4, 4, 5, 5, 1]
const newArr = []
arr.forEach((item) => {
if (newArr.indexOf(item) === -1) {
newArr.push(item)
}
})
console.log(newArr)
3.new Set()
var arr = [1, 2, 4, 4, 5, 5, 1]
const setInstance = new Set(arr)
console.log(setInstance) //Set(4) {1, 2, 4, 5}
//方法1:Array.from将类数组对象或可迭代对象转化为数组。
const newArr = Array.from(setInstance)
console.log(newArr) //(4) [1, 2, 4, 5]
///方法2:展开语法(构造数组时)
const newArr2 = [...setInstance]
console.log(newArr2) ////(4) [1, 2, 4, 5]
4.filter
var arr = [1, 2, 4, 4, 5, 5, 1]
//indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
//filter返回新数组
const newArr = arr.filter((item, index) => {
return arr.indexOf(item) === index
})
console.log(newArr) //(4) [1, 2, 4, 5]
网友评论