Can someone help with this example:
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];
const word = cities.reduce((acc, currVal) => {
return acc + currVal[0];
}, "C");
console.log(word) //CODECADEMY
How does this work?
Iβll suggest two things:
- add log statements to get at the heart of the matter
- get good grounding by reading documentation.
If you modify the function to
const word = cities.reduce((acc, currVal) => {
console.log(acc);
console.log(currVal[0]);
return acc + currVal[0];
}, "C");
youβll start to get the picture.
Then widen the perspective by reading more here: Array.prototype.reduce() - JavaScript | MDN
3 Likes
Ty, Iβll try that code. Iβve been looking at MDN and W3 for the past 3 days. Iβm not getting and clarity lol. The way they explain things confuses me. Iβll keep trying tho.
Itβs a learning curve, but keep trying because once you can read documentation thereβs nothing holding you back from learning anything programming language related. If you make it a habit, eventually you will get it.
To explain the reduce function simply:
It takes an array of values applies one operation to all of them. The operation can be complex but it helps to start with simple operations like add and multiply.
If you reduce [1,2,3,4] with the +
operation, it will give you 1+2+3+4 β 10
If you reduce [1,2,3,4] with the *
operation, it will give you 1*2*3*4
β 24.
If you reduce [β1β,β2β,β3β,β4β] with the +
operation it will give you β1β+β2β+β3β+β4β β β1234β (note, these are strings).
The mdn docs call the operation reducer
. But another way to think about it is myArray.reduce(specificOperation)
= apply my specificOperation to all the elements of my array @digital8364790792
1 Like
On another note, do you know how to get the student discount for this site?
You probably want to try Contact Us
under Help Center
in the codecademy website if you need assistance with that. They should get back to you soon.
1 Like