Reduce method with javascript. Help me to understand the ouput, please

const cities = [‘Orlando’, ‘Dubai’, ‘Edinburgh’, ‘Chennai’, ‘Accra’, ‘Denver’, ‘Eskisehir’, ‘Medellin’, ‘Yokohama’];

const word = cities.reduce((acc, currVal) => {
return acc + currVal[0]
}, “C”);

Output : CODECADEMY

1 Like

The .reduce() method permits us to specify the initial value of the accumulator, which in the above is the letter C. To that the method concatenates the first letter of each string in the array, returning the result shown.

If we do not specify the initial value of the accumulator we run into difficulty:

const cities = ['Columbo', 'Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];

const word = cities.reduce((a, c) => a + c[0])

console.log(word)    //  ColumboODECADEMY

If we attempt to use,

const word = cities.reduce((a, c) => a[0] + c[0])

console.log(word)    //  CY

Of course neither result is correct, requiring us to specify the initial value of the accumulator to resolve this issue.

3 Likes

Thank you so much for you helping

1 Like

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