javascript - 将对象数组与另一个数组循环函数进行比较

标签 javascript arrays function loops object

很抱歉这太长了,但我陷入困境并试图找出为什么我没有获得值。

此函数应返回作为参数给出的所有 Actor 在其中表演的电影数量。

例如:findNumOfMoviesByActors(["Morgan Freeman", "Bob Gunton"]) 应返回 1,因为只有一部电影两者都在其中(请参见下面的数组)。

这是一大堆电影,但这是一个片段:

const movies = [
  {"title": "Beetlejuice",
    "actors": "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page"},

  {"title": "The Cotton Club",
    "actors": "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee"},

  {"title": "The Shawshank Redemption",
   "actors": "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler"},

  {"title": "Crocodile Dundee",
   "actors": "Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil"}]
 

这是我到目前为止的代码:

const findNumOfMoviesByActors = actors => {
      for (i = 0; i < movies.length; i++) {
            movies[i].actors = movies[i].actors.split(' ')
        }
    
      for (i = 0; i < movies.length; i++) {
          let count = 0
          if (actors === movies[i].actors) {
              count++
          }
          return count
      }
  }
    
    const actorCheck = ["Paul Hogan", "Linda Kozlowski"]
    let test = findNumOfMoviesByActors(actorCheck)
    console.log(test)

最佳答案

您需要用可能的空格来分割字符串,因为您会为电影的第二个 Actor 获得一个前导空格,然后您需要迭代所需的 Actor 或给定的 Actor 并计算电影的出现次数。

如果电影包含所有想要的 Actor ,则增加电影计数。

const
    findNumOfMoviesByActors = actors => {
        let movieCount = 0;
        for (let i = 0; i < movies.length; i++) {
            let count = 0;
            for (const actor of movies[i].actors.split(/,\s*/)) {
                if (actors.includes(actor)) count++;
                if (count === actors.length) {
                    movieCount++;
                    break;
                }
            }                
        }
        return movieCount;
    },
    movies = [{ title: "Beetlejuice", actors: "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page" }, { title: "The Cotton Club", actors: "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee" },  { title: "The Shawshank Redemption", actors: "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler" },  { title: "Crocodile Dundee", actors: "Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil" }],
    actorCheck = ["Paul Hogan", "Linda Kozlowski"];
    
let test = findNumOfMoviesByActors(actorCheck);
console.log(test)

关于javascript - 将对象数组与另一个数组循环函数进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62496474/

相关文章:

javascript - 将文本转换为链接的 Tampermonkey 脚本

javascript - Bootstrap 4 可折叠卡片 - 断断续续的动画

javascript - 如何在 For...of 循环中替换数组中的所有 NaN 值

PHP 插入 HTML 表单值注意数组到字符串的转换

r - 根据r中的列名从列表中提取数据框

javascript - 在 angularJS 上更改页面时设置加载程序

javascript - 手动滚动到 anchor 时更改 url?

c - typedef string c 赋值给位置

c++ - 什么是纯函数?

c++ - 带有 Armadillo 可选参数的函数