.recuce() on an array of strings

const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];
const word = cities.reduce((acc, currVal) => {
    return acc + currVal[0]
  }, "C");

The above logs CODEACADEMY to the console. I understood how the .reduce iterator method worked on an array of numbers earlier; but I’m struggling to understand how this works here.

If someone could please explain how this works, it would be much appreciated.

Hi,
it’s similar to numbers only when you add strings together with a + you combine the two strings.
e.g. “A” + “B” = “AB”
So, for this it’s reducing cities by adding them together into one long string, starting with an initial value of “C”.
But, as it’s going through the list, currVal[0] means it’s only adding the first index of each item in the list.
So, instead of “Orlando”, it’s just adding the “O” (the char at index 0).
For “Dubai”, it’s adding “D”.
and so on.

Hope that helps

1 Like

So, correct me if I’m wrong but a few questions come to mind.

  1. “C” –is effectively the second parameter of the reduce “callback function.”
  2. “C” has now taken the place of the first accumulator value.
  3. When we return acc + currVal[0] we are essentially returning the final accumulator value – i.e. CODECADEMY.

Present comment on the three questions and the logic of the table.

Sincere thanks for all your help.

Hi,

  1. It’s the second, optional, parameter of reduce. The callback function is the first.
    Array.prototype.reduce() - JavaScript | MDN
  2. The acc is starting with a value “C”, instead of “”. If instead of “C” it was “BANANA”, then the result would be “BANANAODECADMY”.
  3. While it’s working through the array, the return value is the acc value of the next pass.
    So, first time;
    acc starts out as “C” (would start as “” if “C” wasn’t there)
    currVal is “Orlando”
    it returns back acc + currVal[0] which then becomes acc is the next pass
    so, now;
    acc is “CO”
    currVal is “Dubai”
    and keeps looping round till it’s gone through the cities array and the final value is returned to word.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.