Fireship · @fireship
Array Reduce in 100 seconds
Uploaded December 26, 2019 · Length 1:41
Summary
learn how to use array reduce to compute a single value from a list of items in javascript
- array reduce
- javascript reduce
- array methods
- javascript array
- programming basics
Transcript preview
The first 2 minutes of the transcript. Select a timestamp to watch that moment on YouTube.
- 0:00
arrey reduce start with a list of items
- 0:01
then iterate over them to compute a
- 0:04
single value it works just like basic
- 0:06
arithmetic consider one plus two plus
- 0:08
three what we have here is a list of
- 0:10
numbers they're reduced to a single
- 0:12
value using a function called addition
- 0:14
in arithmetic we go from left to right
- 0:16
the results of the first computation is
- 0:18
then added to the next one so it's
- 0:20
actually just a loop but a loop with a
- 0:22
memory take for example in array of
- 0:25
orders from our online store our goal is
- 0:27
to calculate the total dollar amount of
- 0:28
sales across all of the orders in this
- 0:30
array one option is to create a variable
- 0:33
that starts at zero then we'll start a
- 0:34
for loop and increment this value for
- 0:36
each order total reduce can solve the
- 0:38
same type of problem but without
- 0:40
mutating the appstate directly it does
- 0:42
this by applying a reducer function to
- 0:45
each element in that array your job is
- 0:47
to define the reducer function the
- 0:49
signature of that function has two
- 0:50
required positional arguments the first
- 0:52
one being the accumulator that's just a
- 0:54
fancy word for the last value that you
- 0:56
returned from this function the second
- 0:58
argument represents the current element
- 1:00
in the loop or in our case and ordered
- 1:02
object the way we change the accumulated
- 1:04
or remembered value is to return a value
- 1:06
from the function to combine all of the
- 1:08
order totals into a single number we
- 1:10
simply add the accumulated value to the
- 1:12
current value and optionally we can add
- 1:15
a starting value as a second argument
- 1:16
which will set at zero the end result is
- 1:19
the combined order total across all
- 1:20
elements in the array we started with
- 1:22
many things and reduced it down to one
- 1:24
thing in some cases you might want to
- 1:26
start at the end of the array and work
- 1:27
your way backwards you can use reduced
- 1:29
write to start at the end of the array
- 1:30
and work your way to the beginning this
- 1:33
has been array reduce and 100 seconds
- 1:35
thanks for watching and I will see you
- 1:37
in the next one
- 1:38
[Music]


