-
Notifications
You must be signed in to change notification settings - Fork 1
/
55_example05_movies_array.js
executable file
·36 lines (27 loc) · 1.33 KB
/
55_example05_movies_array.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// find the movies in 2018 with rating > 4
// sort them by the rating
// in descending order.
// Pick only the title and display on the console.
const movies = [
{ title: 'a', year: 2018, rating: 4.5 },
{ title: 'b', year: 2018, rating: 4.7 },
{ title: 'c', year: 2018, rating: 3 },
{ title: 'd', year: 2017, rating: 4.5 },
];
// Method 01:
// Logic:
// filtering movies with year === 2018 and rating >= 4. This returns an array.
// Applying sort method to the new array. sorting based on rating. let say a.rating = 5, and b.rating = 4.5. then difference is positive number 0.5.
// sort method returns value in ascending order.but in this case, we want values in descending order.Hence, reverse method is applied.
// Now, we want to map the values to the title of the array.
const titles = movies
.filter(movies => movies.year === 2018 && movies.rating >= 4)
.sort((a, b) => a.rating - b.rating)
.reverse()
.map(movies => movies.title)
console.log("titles: ", titles);
// Note:
// filter () method returns = a new array, it only works with an array.
// sort () method = by default it works for numbers and strings. For objects we need to supply a comparition function. it returns value in ascending order.
// reverse () method returns = It changes the order in reverse direction.
// map() method returns = an array.