Javascript - Movies Exercise Vid 23, Ex 7

I have worked myself into a state of confusion by being curious.

The solution for the Movies Exercise for the Javascript course shows a chained manipulation on the array. If I understand correctly, each of the manipulations return a new array.

But if I break up the chained manipulations into each step and observe the output, the output is not coming out as I expected?

app.js

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: 2018, rating: 4.2},
{title: 'e', year: 2018, rating: 4.1},
{title: 'g', year: 2017, rating: 3},
{title: 'h', year: 2018, rating: 4.9}

];

let titles1 = movies
.filter(m => m.year === 2018 && m.rating >= 4);

let titles2 = titles1
.sort((a,b) => a.rating - b.rating);

let titles3 = titles2
.reverse();

let titles4 = titles3
.map(m => m.title);

console.log(β€˜movies’,movies);
console.log(β€˜titles1’,titles1);
console.log(β€˜titles2’,titles2);
console.log(β€˜titles3’,titles3);
console.log(β€˜titles4’,titles4);

output

movies [

{ title: β€˜a’, year: 2018, rating: 4.5 },
{ title: β€˜b’, year: 2018, rating: 4.7 },
{ title: β€˜c’, year: 2018, rating: 3 },
{ title: β€˜d’, year: 2018, rating: 4.2 },
{ title: β€˜e’, year: 2018, rating: 4.1 },
{ title: β€˜g’, year: 2017, rating: 3 },
{ title: β€˜h’, year: 2018, rating: 4.9 }
]
titles1 [
{ title: β€˜h’, year: 2018, rating: 4.9 },
{ title: β€˜b’, year: 2018, rating: 4.7 },
{ title: β€˜a’, year: 2018, rating: 4.5 },
{ title: β€˜d’, year: 2018, rating: 4.2 },
{ title: β€˜e’, year: 2018, rating: 4.1 }
]
titles2 [
{ title: β€˜h’, year: 2018, rating: 4.9 },
{ title: β€˜b’, year: 2018, rating: 4.7 },
{ title: β€˜a’, year: 2018, rating: 4.5 },
{ title: β€˜d’, year: 2018, rating: 4.2 },
{ title: β€˜e’, year: 2018, rating: 4.1 }
]
titles3 [
{ title: β€˜h’, year: 2018, rating: 4.9 },
{ title: β€˜b’, year: 2018, rating: 4.7 },
{ title: β€˜a’, year: 2018, rating: 4.5 },
{ title: β€˜d’, year: 2018, rating: 4.2 },
{ title: β€˜e’, year: 2018, rating: 4.1 }
]
titles4 [ β€˜h’, β€˜b’, β€˜a’, β€˜d’, β€˜e’ ]

My question is, shouldn’t each console log display the respective results of each step in the chained manipulation?

eg. console.log(titles1) is displaying a sorted array?

I may have misunderstood something fundamentally important. Many thanks and hope you are all safe and well in these whacky times.

B

filter() and map() return new arrays while while sort() and reverse() are in place operations that alter the array they are called on and return that altered array. So titles1, titles2 and titles3 are all references to the same array that was sorted and reversed by the time it is logged to the console.

1 Like

I had found that the reverse() method worked on its own without the sort in ES6:

const the_movies = movies
.filter(movie => movie.year === 2018 && movie.rating > 4)
.reverse()
.map(movie => movie.title);

console.log(the_movies);