Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Use the reduce method to return a single value from an array of values.
Snippets from the Video
const prices = [6.75, 3.10, 4.00, 8.12]; // Total: 21.97
let total = 0;
prices.forEach(price => {
total += price;
});
console.log(total);
const names = ['Gary', 'Pasan', 'Gabe', 'Treasure', 'Gengis', 'Gladys', 'Tony'];
// Result: 4
MDN Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
The two array methods we just covered,
map and filter, return arrays.
0:00
Sometimes you need to analyze all
of the elements in an array and
0:05
return just a single value,
like a number, string, or object.
0:09
For example,
you might have an array of prices and
0:13
you wanna get a single value,
the total of all the prices.
0:16
With the reduce method,
0:19
you can use the elements of an array to
compute and return any value you want.
0:21
The reduce method lets you turn all
the items in an array into one value.
0:26
If you had an array of names, for example,
and you wanted to find out how many names
0:31
there were with a length greater than six,
you could use reduce to return that total.
0:36
You could also add an array of
numbers together and return the sum.
0:41
Or say you have an array of dates and
you want to return the most recent date.
0:46
Reduce can do all of this and more.
0:50
The parameters for
0:54
reduce work a little differently
than the methods we've seen so far.
0:55
I'm on the MDN documentation page for
reduce.
0:59
This page has a lot of information and
I'd encourage you to read it over.
1:02
For our purposes,
let's look at this example down here.
1:07
Which returns the sum total
of all numbers in an array.
1:11
Notice the callback passed into reduce,
1:17
has two parameters instead of the one
we've been using with filter and map.
1:21
The first parameter is
called an accumulator
1:26
represented here by the parameter acc.
1:28
The second parameter,
cur, in this example,
1:32
short for current,
represents the current array item.
1:35
The accumulator is very important.
1:39
It contains the running total of
the value the reduce method returns.
1:42
The accumulator is kind of
like a shopping basket.
1:47
When you go shopping for groceries,
1:50
you need to have some container or
basket to hold all of those groceries.
1:52
Every time you pick up a new item,
you have two things,
1:57
the item itself, and
the basket of previous items.
2:01
You can combine those two things by
placing your new item in the basket, and
2:06
moving to the next food item you need.
2:10
The reduce method works in the same way.
2:13
The basket is like the accumulator
that accumulates groceries.
2:15
Each food item is like
a new item from the array.
2:20
At the end of the array, the accumulator,
the basket, is returned.
2:23
Let's look at the MDN example again.
2:29
The callback receives an accumulator,
acc, and the array item, cur.
2:32
Then it's returning the sum
of these two values.
2:37
Whatever the callback returns
becomes the accumulator for
2:42
the next time in the array.
2:45
When the end of the array is reached,
the final value of the sum is returned.
2:47
What about the first time
reduce runs on an array?
2:52
You might think there's no value
to serve as the accumulator.
2:56
That's where the second argument after
the callback function comes into play.
3:00
This argument sets the value
of the accumulator for
3:05
the first time in the array.
3:08
In this example, since the callback
adds up all the items in the array
3:10
the accumulator starts at zero.
3:15
Then, it increases as reduce
moves through the array,
3:17
adding each item to the accumulator.
3:21
I'm just going to copy
this code snippet and
3:24
paste it into my workspace so
we can see it run.
3:27
I'll add a line to log to
the console as well, to log total.
3:33
If I run it.
3:44
You can see six is logged out.
3:49
Which is what we expected.
3:52
0 plus 1, plus 2, plus 3 is 6.
3:53
Now, I'll just remove the second
parameter and run it again.
3:57
And it still works.
4:07
If an initial value for
the accumulator is not given,
4:09
reduce will take the first element of
the array and use it as the initial value.
4:13
The first element is zero,
so the first time through,
4:18
the accumulator will be zero,
and cur will be one.
4:22
For this case,
where we get the same result with or
4:27
without an initial value, I'd rather
use the second parameter with reduce.
4:29
It makes the initial value explicit.
4:36
If I come back to a reduce statement
I wrote a few months ago for
4:38
example, I can tell right away what
value the accumulator starts with.
4:42
Why don't you run through
a simple example to this one now.
4:47
Refactor the code we wrote
previously to add prices together.
4:51
You can copy this snippet from
the teacher's notes below.
4:58
Use reduce instead of forEach, to add
these prices together and log the result
5:01
To refactor this code,
I'll first change the forEach to reduce.
5:09
Then I'll set total to equal
the output of the reduce call.
5:17
Then I'll change let to const.
5:23
The callback takes an accumulator and
an array item.
5:26
So I'll add an accumulator and
I'll call it sum.
5:30
We want to return the sum of
the accumulator and the current price.
5:37
So sum.
5:44
Plus the current price.
5:50
Finally, I'll add an initial value for
the accumulator, zero.
5:54
I'll save it and run.
5:59
It works as expected.
6:04
Now that you have a feel for
how reduce works,
6:05
I'm going to challenge you to solve a
problem that requires a little more logic.
6:08
I'll clear the console.
6:13
And I'll replace this code
with an array of names.
6:18
See if you can return account of
the names that begin with the letter G,
6:23
using reduce and log it to the console.
6:26
The first thing I'll do is to declare
a new variable to hold the count,
6:34
gNameCount.
6:38
And set it equal to names.reduce.
6:44
And I'll need a callback function.
6:52
I wanna start the count at zero so
I'll enter that for the second parameter.
6:58
And I'll put a parameter count for
my accumulator and
7:07
use name for the array items.
7:12
If name starts with G,
I wanna return count plus one.
7:15
Earlier, I used the char at method
to get the first letter of a name.
7:23
This time, I'll use a different way.
7:27
The characters in a JavaScript string
can also be referenced by index,
7:29
like an array.
7:34
I'll use square brackets to get
a reference to the first position of
7:35
the string, which has an index of zero.
7:38
And then I wanna return, count + 1.
7:50
If the name doesn't start with G,
I'll just return count without adding one.
7:58
And then I'll log
gNameCount to the console.
8:05
I'll save and run this.
8:17
And you see, we get four.
8:21
And there's four gNames in the array.
8:23
So far, we've just been getting our feet
wet with the array methods filter, map,
8:27
and reduce.
8:32
These methods are capable of a lot
more than you've seen so far.
8:33
And often handle more complex problems
than the ones we've been learning with.
8:37
In the next videos, we'll work
through some bigger problems, so
8:41
you can see how helpful
these methods can be.
8:44
It's gonna be fun, see you there.
8:47
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up