Reduce() method

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) => {
  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


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