const cities = [‘Orlando’, ‘Dubai’, ‘Edinburgh’, ‘Chennai’, ‘Accra’, ‘Denver’, ‘Eskisehir’, ‘Medellin’, ‘Yokohama’];
const word = cities.reduce((acc, currVal) => {
return acc + currVal[0]
}, “C”);
Output : CODECADEMY
const cities = [‘Orlando’, ‘Dubai’, ‘Edinburgh’, ‘Chennai’, ‘Accra’, ‘Denver’, ‘Eskisehir’, ‘Medellin’, ‘Yokohama’];
const word = cities.reduce((acc, currVal) => {
return acc + currVal[0]
}, “C”);
Output : CODECADEMY
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.
Thank you so much for you helping
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.