1. includes
新建一新空数组,遍历传入数组,值不在新数组就push进该新数组中,
includes
与indexOf
原理相同。
let reg = [1, 1, 2, 2, 22, 4, 4, 6, 6, 8]
let arr=[]
reg.forEach(item => {
if (!arr.includes(item)) {
arr.push(item)
}
})
2. indexOf
let arr=[]
reg.forEach(item => {
if (arr.indexOf(item)==-1) {
arr.push(item)
}
})
3. reduce
语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
- total:初始值,或者计算之后的返回值
- currentValue:当前元素
- currentIndex:当前元素的索引
- arr:当前元素所属的数组对象
- initialValue:传递给函数的初始值
reg.reduce((total, value) => {
return total.includes(value)?total:total.concat(value)
}, [])
Set
ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。我们发现得到的结果,是一个对象,并不是数组,可以使用Array.from(),它可以把类数组对象、可迭代对象转化为数组。
- 展开运算符和set结构
let cie=[...new Set(reg)]
- Array.from()来实现方法扩展运算符的功能
let cie=Array.from(new Set(reg))
- Set 可以很容易地实现并集(Union)、交集(Intersect)和差集(Difference)
let a=new Set([1,2,3])
let b=new Set([2,4,5])
//并集
let union = new Set([...a,...b])
//Set(5) {1, 2, 3, 4, 5}
// 交集
let intersection = new Set([...a].filter(x => b.has(x)));
//Set(1) {2}
// 差集
let difference = new Set([...a].filter(x => !a.has(x)));
//Set(2) {1, 3}