需求 : 计算数组1中与数组2不重复的项取出放在新数组中
初级版
原理:
1.使用for…each遍历数组2获得每一项item
2.在循环中使用findIndex方法遍历数组1每一项it判断是否包含item,包含返回索引值,不包含就返回-1
3.判断findIndex返回的索引值,若为-1,就将当前的item项push到新数组中
const arr1 = [{ id: 1, name: 'a' }]const arr2 = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }]const arr3 = []arr2.forEach(item => {const idx = arr1.findIndex(it => {return item.id === it.id})if (idx === -1) {arr3.push(item)}})
2. 使用
import arrSub from 'xxx'// 定义两个数组 作省略...computed: {// 计算属性recommendChannels () {return arrSub(this.allChannel,this.channels)}}
进化版
原理
1.使用filter遍历数组2将满足条件的item返回并添加到新数组中
2.在循环中使用findIndex方法遍历数组1每一项it判断是否包含item,包含返回索引值,不包含就返回-1
3.将idx作为filter回调函数的返回值,,如果为true就将当前item项添加到新数组中
const arr1 = [{ id: 1, name: 'a' }]const arr2 = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }]const arr3 = arr2.filter(item => {const index = arr.findIndex(it => (it.id == item.id))return (index === -1)})
终极进化版
原理
1.使用filter遍历数组2将满足条件的item返回并添加到新数组中
2.在循环中使用some方法遍历数组1每一项判断it中是否存在与item不相等的项,存在就返回true
3.将some方法中返回true的item项添加到新数组中
const arr1 = [{ id: 1, name: 'a' }]const arr2 = [{ id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }]const arr3 = arr2.filter(item => {return arr1.some(it => item.id != it.id)})
