Help understaind reduce.arr line of code

Can someone walk me through how the bold line of code works? Got it from stackoverflow and it solves my issue, but I don’t understand how. Any help is much appreciated! :slight_smile:

const jurassicParkMovies = [
one: “Jurassic Park”,
two: “The Lost World: Jurassic Park”,
three: “Jurassic Park III”,
four: “Jurassic World”,
five: “Jurassic World: Fallen Kingdom”,
six: “Jurassic World: Dominion”,
const seeJPMovies = ({ one, two, three, four, five, six }) => {
seeJPMovies({ …jurassicParkMovies.reduce((a, c) => ({ …a, …c }), {}) })

The reduce method is used to “reduce” the items in an array down to a single value. Just keep in mind that the single value doesn’t have to be a number, it can be a single object. Check out this “plain English” explanation of how reduce works.

The potentially complicating factor here is use of the spread syntax (the three dots). Check out this explanation of spread syntax, which pretty much has an example that does exactly what you are doing in the reducer callback function, except with arrays.

It might be easier to move the reduce out to its own line (to reduce complexity) and then you can add console.logs to print out values so you can see what is happening in each iteration through the array.

const reduced = jurassicParkMovies.reduce((a, c) => {
    return { ...a, ...c };
}, {});


I’ll let you add the console.logs :slight_smile:

P.S. For this particular example there is a much simpler way to get the arguments you want to pass into seeJPMovies(). Once you understand spread syntax you might realize that you don’t need the reduce method at all.

1 Like

Thank you :slight_smile: