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

Ame*_*a W 2 javascript arrays loops function object

很抱歉这太长了,但我被卡住了,并试图弄清楚为什么我没有得到价值。

这个函数应该返回所有作为参数给出的演员在其中表演的电影数量。

例如: 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"}]
 
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 5

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

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

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)
Run Code Online (Sandbox Code Playgroud)