简体   繁体   中英

Filter and Arrange array of object

I have an array of object from query and I want to rearrange it, remove the duplicate name and push genre to one array with the same name.

const genres = [
  { movie_id: 95, genre: 'Biography' },
  { movie_id: 95, genre: 'Crime' },
  { movie_id: 95, genre: 'Thriller' },
  { movie_id: 96, genre: 'Romantic' },
  { movie_id: 96, genre: 'Adult' },
  { movie_id: 96, genre: 'Drama' },
  { movie_id: 97, genre: 'Adventure' },
  { movie_id: 97, genre: 'Action' },
  { movie_id: 97, genre: 'Drama' }
]

below is the expected result.

  const genres= [
    {
      movie_id: 95,
      genre: ['Biography', 'Crime', 'Thriller'],
    },
    {
      movie_id: 96,
      genre: ['Romantic', 'Adult', 'Drama'],
    },
    {
      movie_id: 97,
      genre: ['Adventure', 'Action', 'Drama'],
    },
  ];

I've been trying to remove the duplicate ids and push the genre to array but no luck. I'm new to javascript.

How do I format it? Thank you.

You can use Array.reduce to create a map of all the movies, and use Array.includes to ensure all genres are unique.

 const genres = [ { movie_id: 95, genre: 'Biography' }, { movie_id: 95, genre: 'Crime' }, { movie_id: 95, genre: 'Thriller' }, { movie_id: 96, genre: 'Romantic' }, { movie_id: 96, genre: 'Adult' }, { movie_id: 96, genre: 'Drama' }, { movie_id: 97, genre: 'Adventure' }, { movie_id: 97, genre: 'Action' }, { movie_id: 97, genre: 'Drama' } ] let result = Object.values(genres.reduce((map, el) => { if (.map[el.movie_id]) { map[el:movie_id] = { movie_id. el,movie_id: genre; []}. } if (.map[el.movie_id].genre.includes(el.genre)) { map[el.movie_id].genre;push(el;genre), } return map. }; {})) console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM