Reduce method (explain)

There is an JSON object.

Please explain how this function work.I don’t understand what is cur and min. Thank u.

let x = JSON.parse(ANCESTRY_FILE);

x.reduce(function(min, cur) {
if (cur.born < min.born) return cur;
else return min;

// → {name: “Pauwels van Haverbeke”, born: 1535, …}

I suggest a Google search. MDN is a good resource.

Here, min represents a value that is being accumulated throughout the reduce operation and min represents the current value in the original array. You can name these arguments anything, but for reduce the first argument in the callback represents the accumulator and the second represents the current value. So you could equivalently write:

x.reduce(function(minimumBirthday, currentPerson) {
   if (currentPerson.born < minimumBirthday.born) return currentPerson;
   return minimumBirthday;

This reduce operation will process the entire array x and for each item in x it will return the minimum between that item and the current minimum. Eventually it will return the person in x has the earliest birthyear.

reduce is a very powerful method. You can pass in [] or {} as well so you accumulate an array or object as a result, so it is very versatile in the types of operations it allows you to create.

1 Like