0

I want to collect all the movie id's where in rating is above 3 from the below array

let movies = [
  {'name': 'Actions', 'movies': [{'id': 1, 'rating': 2}, 
                                 {'id': 2, 'rating': 1}, 
                                 {'id': 3, 'rating': 4}]},
  {'name': 'Comedy', 'movies': [{'id': 4, 'rating': 3}, 
                                 {'id': 5, 'rating': 4}, 
                                 {'id': 6, 'rating': 5}]},
  {'name': 'Sci-fi', 'movies': [{'id': 7, 'rating': 1}, 
                                 {'id': 8, 'rating': 5}, 
                                 {'id': 9, 'rating': 2}]}
];

I'm getting the id's with rating above 3 from below code

let res = movies
          .map( m => m.movies
                    .filter( f => f.rating > 3 ) 
          )
          .flat();
console.log(res);

output

[[object Object] {
  id: 3,
  rating: 4
}, [object Object] {
  id: 5,
  rating: 4
}, [object Object] {
  id: 6,
  rating: 5
}, [object Object] {
  id: 8,
  rating: 5
}]

How can i get rid of [object Object] and rating from my output and get only flatted id's array?

0

3 Answers 3

2

Flatten the movies to an array using Array.flatMap(), filter by the rating, and then map to ids:

const movies = [{"name":"Actions","movies":[{"id":1,"rating":2},{"id":2,"rating":1},{"id":3,"rating":4}]},{"name":"Comedy","movies":[{"id":4,"rating":3},{"id":5,"rating":4},{"id":6,"rating":5}]},{"name":"Sci-fi","movies":[{"id":7,"rating":1},{"id":8,"rating":5},{"id":9,"rating":2}]}];

const result = movies
  .flatMap(m => m.movies)
  .filter(m => m.rating > 3)
  .map(m => m.id);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a forEach() loop:

const movies = [{
  "name": "Actions",
  "movies": [{
    "id": 1,
    "rating": 2
  }, {
    "id": 2,
    "rating": 1
  }, {
    "id": 3,
    "rating": 4
  }]
}, {
  "name": "Comedy",
  "movies": [{
    "id": 4,
    "rating": 3
  }, {
    "id": 5,
    "rating": 4
  }, {
    "id": 6,
    "rating": 5
  }]
}, {
  "name": "Sci-fi",
  "movies": [{
    "id": 7,
    "rating": 1
  }, {
    "id": 8,
    "rating": 5
  }, {
    "id": 9,
    "rating": 2
  }]
}];

let result = [];

movies.forEach(({movies}) => {
  var movie3 = movies.filter(({rating}) => rating > 3).map(({id}) => id);
  result = [...result, ...movie3];
});
console.log(result);

1 Comment

Which is just a "complicated" way of .map()
1

You can get the desired output by adding map(rw => rw.id) after flat function.

let res = movies
          .map( m => m.movies
                    .filter( f => f.rating > 3 ) 
          )
          .flat().map(rw => rw.id);
console.log(res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.