一个数组(列)“减去”一个数组“列”

问题描述

  现已知“我的频道”列表数据(userChannels),和“全部频道”列表数据(allChannles),想要获取后者减去前者之后能够得到的数组。

我的使用

  JavaScript中数组的filter()和find()方法。

  1. Array.filter()

    filter(value,index,array)方法创建一个满足指定条件的新数组。

    此函数接受 3 个参数:

      项目值

      项目索引

      数组本身

       2. Array.find()

             find(value,index,array))方法返回通过测试函数的第一个数组元素的值。

    此函数接受 3 个参数:

      项目值

      项目索引

      数组本身

代码实现

recommendChannels () {
          // 所有频道 - 我的频道 
          // filter 方法: 过滤数组,根据方法返回的布尔值 true 来收集数据
         return this.allChannels.filter(channel => {
                // 判断 channel 是否属于 userChannels
          // console.log("channel",channel)
// 查找 对于这个 channel 如果找到了,则 !一下 return !this.userChannels.find( userChannel => { // 找到满足该条件的元素 相同 返回 true
            // console.log("userChannel",userChannel)
           return userChannel.id === channel.id }) })
}

控制台中打印结果分析:首先打印allChannels的第一个数值,然后遍历userChannels,直到找到相同项或者找不到遍历结束为止。

上述方法其实相当于

const arr = []
        // 遍历所有频道
        this.allChannels.foreach( channel => {
            const flag = false
            for( let i = 0; i < this.userChannels.length; i++) {
                if( userChannels[i].id === channel.id){
                    flag = true
                    break;
                }
                if(!flag){
                    arr.push(channel)
                }
            } 
        })
        return arr

 

posted @ 2021-07-09 10:55  Fron-temper  阅读(134)  评论(0)    收藏  举报