Home > Mobile >  Compare a nested array with another array
Compare a nested array with another array

Time:03-23

I have two array one is Movie List and another is Genre

Requirement:

Need to compare both the array and filter the movies according to its genre.

1.Example for Movie List

movietList = [
  {
    title: "The Dark Knight",
    genre: "Action"
  },
  {
    title: "The Godfather",
    genre: "Crime"
  },
  {
    title: "The Shawshank Redemption",
    genre: "Drama"
  },
]

2.Example for Genre

genre = [Action, Crime, Drama]

3.Expected Result

result = [
  action: {
     title: "The Dark Knight"
      },
  crime: {
     title: "The Godfather"
     },
  drama: {
     title: "The Godfather"
     }
]

CodePudding user response:

you will need array.reduce method to group movie by genre

you can have several movie with same genre so elements grouped should be place in an array []

var movieList = [
  {
    title: "The Dark Knight",
    genre: "Action"
  },
  {
    title: "The Godfather",
    genre: "Crime"
  },
  {
    title: "The Shawshank Redemption",
    genre: "Drama"
  },
  {
    title: "The Shawshank Redemption 2",
    genre: "Drama"
  },
];

let result = movieList.reduce((acc, current) => {
  const genre = current.genre.toLowerCase();
  (acc[genre] = acc[genre] || []).push({
    title: current.title
  });
  return acc;
}, {});

console.log(result);

CodePudding user response:

const movietList = [
    {
        title: "The Dark Knight",
        genre: "Action"
    },
    {
        title: "The Godfather",
        genre: "Crime"
    },
    {
        title: "The Shawshank Redemption",
        genre: "Drama"
    },
];

const genres = ["Action", "Crime", "Drama"];


const groupBy = (movietList.reduce((acc, {title, genre}) => {
    if (!genres.includes(genre)) {
        acc[genre] = []
    }
    else {
        acc[genre.toLowerCase()] = {title}
    }
    return acc;
}, {}));


console.log(Object.entries(groupBy).flat());

  • Related