【问题标题】:Find the same elements of an array from other arrays?从其他数组中找到一个数组的相同元素?
【发布时间】:2020-04-18 04:55:32
【问题描述】:

我有一部电影,我想放映相同类型的电影,我做错了什么?

我的电影(查找):

{
    "id": 1,
    "title": "Kill Bill",
    "genre_ids": [1, 10, 15]
}

//所有电影(电影)

{
    "id": 2,
    "title": "Leon",
    "genre_ids": [1, 12, 15]
},
{
    "id": 3,
    "title": "Spider-man",
    "genre_ids": [12, 32, 15]
},
{
    "id": 3,
    "title": "Marvel cap",
    "genre_ids": [20, 38, 1]
},

// 我的代码

    return find.map(i => { // My film
        return i.genre_ids.map(ids => {
            return movies.data.results.filter(movie => { // All films
                return movie.genre_ids.filter(idMov => idMov === ids)
            })
        })
    });

【问题讨论】:

    标签: javascript reactjs loops


    【解决方案1】:

    您的电影(查找)是一个对象,而不是数组,它没有要调用的 map 函数。

    解决方案:

    创建一个函数,该函数可以从单个流派和电影数组返回按流派匹配的电影数组

    const matchByGenre = movies => genre =>
      movies.filter(movie => movie.genre_ids.includes(genre));
    

    遍历影片的 genre_ids 数组以进行匹配。这会产生一个数组匹配数组,用.flat 将它们展平为单个数组。该集合用于删除重复项并将结果作为数组返回给您。

    const movieSet = Array.from(
      new Set(film.genre_ids.map(matchByGenre(movies)).flat())
    );
    

    const film = {
      id: 1,
      title: "Kill Bill",
      genre_ids: [1, 10, 15]
    };
    
    const movies = [
      {
        id: 2,
        title: "Leon",
        genre_ids: [1, 12, 15]
      },
      {
        id: 3,
        title: "Spider-man",
        genre_ids: [12, 32, 15]
      },
      {
        id: 4,
        title: "Marvel cap",
        genre_ids: [20, 38, 1]
      },
      {
        id: 5,
        title: "The Big Lebowski",
        genre_ids: [20, 38, 2]
      }
    ];
    
    const matchByGenre = movies => genre =>
      movies.filter(movie => movie.genre_ids.includes(genre));
    
    const movieSet = Array.from(
      new Set(film.genre_ids.map(matchByGenre(movies)).flat())
    );
    
    console.log(movieSet);

    注意:如果matchByGenre 的语法令人困惑,它是一个柯里化函数,接受一个电影数组并返回一个供array::map 使用的回调函数

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多