Master JavaScript Array Reduce Method In 10 Minutes

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone today we're talking about javascript's array.reduce method which is definitely the hardest of the array methods but of course it's also a must know hate it when that happens all right here we go so reduce is in the same family of array methods as for each and map and filter Each of which are going to accept a callback and then call that callback with every single element from the array one at a time of course they differ in what they actually do after that point but they all follow that same pattern you pass through a callback and it's executed once for every element in the array reduce is similar in that we do provide a callback and that callback will be executed for five and then for three and then nine and then eight if this is the array we're using but there's also a second parameter in here and there's a second argument and there's some funky stuff going on that makes reduce a lot trickier to pick up when you're starting out so first of all if you don't know for each map and filter I would start there and then come back because reduce is a little confusing but it's also so very flexible and Powerful the first thing to know is that reduce expects a callback function and at the end of the day it's going to return to us a single value now that value might be a primitive like a single number we can take an array of numbers and reduce it down to a sum 28 is the sum of all these numbers or it could be the maximum number in this case is 9. so that's a value we could find using reduce or the minimum but we're not limited to actual numbers we could work with an object as the return value of reduce this is a frequency map telling me a occurs twice in this array B occurs 3 times F once so it's an array of values that are reduced down to a single thing whatever that thing is here's one more example an array of arrays two dimensional we could use reduce to flatten into a single one-dimensional array and what makes it all possible is the mechanic underlying reduce so our callback function is not only going to be passed each element one at a time from the array but it's also passed through whatever value was returned from the previous execution of the Callback so there's this thread tying together each iteration we can pass the value through we can preserve a value preserve the sum and keep adding on to it or the maximum and keep updating what the maximum is or this object with frequencies we keep updating that every time the Callback is executed so one more time I'm going to show this to you in code it will make a lot more sense if you're confused but whatever callback we write and pass to reduce it will be provided the value returned from the previous execution of the Callback so reduce expects a callback that has two parameters and that first parameter call it whatever you want that is what will be passed the previous return value so whatever we returned last time from this callback will be stored under previous Val and then current Val the second parameter call it whatever you want uh it's just going to refer to one element from the array one at a time in order so you know it will start as five and then three and then nine just like for each map filter all of them and then there's an optional second argument which is after the Callback this second argument will be used to set the initial value for that first parameter it's all very confusing but remember if this is supposed to refer to whatever we returned last time the Callback ran that's great but the very first time there was no last time so what does it refer to that's what that second argument is for so in this case previous would start as an empty object in this case total starts at zero so let's look at an example this is a simple example very classic reduced 101 example of summing the numbers in an array and this diagram kind of shows the flow of information from one callback to the next so uh or one callback execution to the next we have our numbers five three and nine we have two parameters in our callback sum that will refer to whatever is returned from the Callback but it starts at zero and then current Val will hold one of these numbers in the array in order one at a time so the first time the Callback is executed sum is zero current Val is five because it starts at the beginning so that means we return 0 plus 5 which is five and then this is the the magic the really important part of reduce that five doesn't just disappear it's stored and passed through as the new value for sum on the second execution so now sum is five current value is three we return 5 plus 3 which is eight and that value is returned and once again plugged back in as the next value for sum on the final iteration eight plus nine return that now we've hit the end of the array the Callback is no longer executed anymore and whatever that final return value is is the total return value or the overall return value of reduce in this case 17. so what powers this whole thing is being able to take whatever we returned last time and have access to it next time or the current time if you will and we can build up the sum one iteration at a time and let me just prove that it works we have our five three and nine array here's the same exact reduce we get 17. now this second argument after the whole callback right that's the first argument right there after that whatever this is is the initial value for our first parameter in that callback so if I started at 1000 we get 1017. probably don't want to start it at 1000 but I can now we don't always need to have a value there and that's what the second example is going to show so this is using reduce to find the maximum element in an array which by the way there is a math.max method probably better to use that but this is another simple example of using reduce so if you think about how you would find the max using reduce where we can preserve one value each iteration we basically keep track of whatever the maximum is as we move around the array from left to right so 45 starts as the max is 23 bigger no so that means 45 is going to be passed through is 98 bigger yes and then we keep track of 98 and we keep comparing and then eventually we figure out 103 is the largest so if we don't provide an initial starting value as a second argument reduce will actually have the first parameter start as the first element in the array and then the current value will Skip and start as the second so we basically begin with 45 and 23 which you don't always want but in the case of something like finding the maximum if we started with zero like that could work but what if our array was all negative zero is a really bad choice then because it's bigger than all of the array elements so if you look at the logic here it's very straightforward it's actually more verbose than it needs to be but it's easy to understand basically if the current value is bigger than the maximum return the current value otherwise return the maximum so we just return whichever one is larger in the very first time Max starts as 45 current value is 23 which one is bigger 45 is returned and then that is remembered for the next time through it's provided us the new value for Max Max is 45 current value is 98 we return 98 because that's bigger then that's remembered I keep saying remembered but it's nothing fancy it's just passed through as the next value for Max is 98 compare that to 25 return 98 that's passed through one more time Maxis 98 current values 103. compare those 103 is bigger that's the end there's no more execution Cycles so that last return value of 103 is the overall return value for this reduced call and that is indeed the maximum so hopefully this example makes it clear or clearer how this process works if having your return value being passed through over and over and over and how we can use that as a tool to preserve some important piece of information in our case the maximum as we progress or in the previous example the running sum as we progress but we're not limited to things with numbers into you know arithmetic or comparisons like this one of the more common uses of reduce is to calculate frequencies or to group data together based upon some existing array-based data structure so here's this example with grades I'm a teacher I have a list of grades a b f b c c a and then down here I'll zoom in a bit I've got a call to reduce where what I'm going to do is build up a frequency object kind I showed this on the slides where it will show something like a is 3 and b is 5. keeping track of how many times each value appears in the array and the way that we do this is by starting out with an empty object so not zero or something but an empty object and then each time through I'm going to look at each grade and check to see if that grade exists in this object at the very first time of course it won't like a the first time it doesn't exist so this is true it's set to null meaning we then add it into this dictionary object and set it to one so a not that would be set to 1. and then we return this object now that has a little value and a little bit of information and then the process repeats next up for B and then F right so those both get set in here a is one B will be set to one f is one and then on the fourth iteration this is what it would look like as it is passed into grades freak frequency but this time grade is B and B already is in there so instead we increment it by one and it goes up to two so this is another example just a very different idea instead of summing things up we're counting and we're building up a larger data structure let me just run this and show you it does work a is three B is five C is three but the concept underpinning it is all about preserving one value between iterations of our callback between each execution but instead of preserving a single number we're now preserving a dictionary or an object that is passed through and modified every time through that callback so I know it can be overwhelming it's confusing I don't expect this video to you know teach you everything or anything necessarily but I hope you get something out of it uh take a look at the slides walk through this put console.logs and just practice with reduce and see if you can understand every step of the way how it works and then eventually you'll start to kind of think in terms of reduce which is the final step and that's it so thanks for watching I hope you learned something if you want to check out any of my courses there's a link here with all the you know coupons and stuff lowest prices I can give you blah blah blah subscribe whatever um and thanks for watching hope you have a great rest of your week and hope you enjoy using reduce
Info
Channel: Colt Steele
Views: 6,602
Rating: undefined out of 5
Keywords:
Id: VOQSrdX82L8
Channel Id: undefined
Length: 10min 50sec (650 seconds)
Published: Tue Nov 01 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.