Reduce: 10 Different Examples. JavaScript Fundamentals.

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey how's it going everyone its Lee holiday I saw this tweet the other day from Ken wheeler and he said other times I'll ask more general questions like ham implement a reduce so I was thinking about how much I love the reduced function how versatile it is and just in case you're getting interviewed by Ken wheeler you'll know this thing rock-solid what we're gonna do today is look at ten examples of how to use reduce and then we're going to implement a simple version of reduce ourselves so to get started we'll open up vs code and I've got some data here it's just an array of three people me and my two sisters and what we're gonna do is implement a whole different number of ways you can use reduce it may not always be the most efficient way if there's a sort of native function in JavaScript that does it you should probably just use that instead but it's a good way to sort of understand and get comfortable using reduce and I'll explain sort of how it looks and how it works in a second as we get into it so the first thing we're going to do is we're going to use reduce to count the number of people in this array you could just say like people dot length right but we're talking about reduced so let's do that we're gonna save our our result in a variable I defined here called result so result is people dot reduce so reduces a function you always call on arrays and you pass a callback function and an initial value so we're counting so let's start at zero as our initial value so our callback will always receive an accumulator so some number that's being passed from one call of this callback function to the next plus each element as its iterating over the people so we'll call this person so what are we trying to do here we're trying to count so what we'll do in this case is in sort of arrow function we'll just take the current accumulator or the sum and we'll add one to it so we'll start at zero zero plus one will return one next time it cuts called for a person will return one plus one is two etc so if I run this will do node index like that and it gives us three so we're finding the correct result so let's make it a little bit harder let's try to find the sum of all the ages so these ages here so people dot reduce same set up a callback function that's called once for each iteration over all the people an initial value so we'll start it at zero again we've got our accumulator and our person so what we can do is return our current accumulator the sum plus the person dot age so rather than just returning one each time we can access a value from the person so if I were to run this 93 so my family my siblings we add up to 93 years old so you don't just have to to count things or some things you can start with any sort of initial value what we're going to do now is cover basically how to use reduce as if you were mapping so we'll say result is people dot reduce callback function initial value will start it as an empty array this time so we're past our accumulator which is this array as we're iterating over the people and the person so I said here we want to return an array of names so what we can do is we can return a new array which is all of the previous names plus the new name we'll tack that onto the end so run this now we have just converted from an array of objects to an array of names which is exactly what map does but we implemented it using reduce this is an example is probably just use map I mean it's it's way easier right but it's good to know how a produce works next and this is something I do all the time say you want to have you want to find in this case you want to find a person by their ID now you could look you could iterate through the array every time you want to find someone but that would be very slow if you had 10,000 people to look through so what I sometimes do is I basically convert this style of Ray to a dictionary where the Heidi is the key and then the object is the value so that anytime you want to access a person you can just access them using the ID rather than having to find them in an array and it is a lot more efficient I'll show you what I mean in a sec so same same thing reduce our people we've got our callback function we've got our initial value this time we'll be an object and we've got our accumulator and we've got our person so what we are going to do is we're gonna produce a new object so when I just do this of a extended format this time so we'll return a new object which will be anything we had before so spread it out plus we want to have imagine we've got person 3 we want to basically have 3 plus that person sort of like that what we can do to do this dynamically is we can say person dot ID that's the key and the value will be the person just like that so if we run this what we end up with is an object or a dictionary or a lookup table or something like that where we've got the key being the person's ID and then its value now for example if you wanted to find someone all you'd have to do is say console dot log result let's find person three like that what did I do oh there we go that one right here so we found Heather just by looking her up using her ID so that is a lot more efficient than looping through the array every time you wanted to find someone cool you can use reduce to find the max value so I'll show you how that would work so we'll do people dot reduce and here again you'd probably I guess you couldn't use um math dot max you'd have to first map map the array to just get numbers and then find the max of those so in this case it's probably more efficient to use reduce but we've got our callback function we've got our initial value I'm gonna just start it as a null here and because I don't want to start a 0 because 0 if they're all negative values 0 would come out as the max value and that doesn't make sense so let's start it as null we've got our accumulator and our person and we'll put a bit of logic in so if the accumulator is currently null or the accumulator is sorry if or the person dot age is greater than our current max number what we'll do is we'll return the person age so the next iteration the accumulator will come in as whatever age we've returned so in this case we're hoping for 35 to come out as our result cool if it if that's not true what we'll do is we'll just return the current accumulator so whatever the current max value is so we run that we find 35 if we want it bonus will do 11 so let's say we'll find the min 8 so when this what the deuce do is we'll swap that I think that's all we have to do and there we go we just found the min age so just to go over it again if we haven't even set a value yet or the age of the person we're currently on is less than the lowest age we've found so far set that return that as your new accumulator value as you're iterating over okay let's try to write a reduce function that will find a person by their name so what we'll do is we'll say we're going to reduce the people call back function let's say no as our initial value and we've got our accumulator and our person so you're getting the pattern over and over again so this logic is a little bit weird and in this case I would probably use the the people that find function because a it's gonna be a lot more efficient and a heck of a lot less confusing but this is just to prove that you can do crazy stuff with produce so what we'll do is we'll say if AK is not equal to null that means we've already found someone so we're just going to return that person basically skip iterating over the rest of the people we've already found them here's why it's not efficient because we say we found the person as the first item in the array it's gonna have to keep looping over the rest of them so don't use this method but that's fine so if we get to the second if statement it means we haven't found the right person yet so what we're gonna do let's just say we're looking for person with the name of Lee so if that matches what we'll do is we'll return that person if we haven't found the person yet we will return that you know meaning it will just keep looking so let's run that and there we go we found my person in the array moving on to the next one let's see if all the people in the array are over 18 years old so people dot reduce call back function um let's start it out as true I may be wrong we'll see let's see think about that we want to assume they all are unless we find one that isn't in which case we'll flip it over to false so we're going to start assuming it's true I don't know we'll see so we've got our accumulator and our person we'll say if if it's already been flipped over to false meaning we've already found someone let's just return false because it's it's still false as soon as one person is not over 18 that means they're not all over 18 otherwise we will return whether the person Dada age is over 18 so run that it's true so if we were to change this to say if they're all over let's say 30 one person that's not over 30 okay next we're going to see if any are over 18 so we don't care if they all are but is one person over 18 I think this is also called some the function in in JavaScript and again if there's a native function use that instead but just to show how it works so people that reduce we have our callback this time we're going to start as false but as soon as we find someone we're going to flip this the flat the switch and make it true so we've got our accumulator and our person so what we're going to do is we're going to say if this accumulator is true it's just it's true forever otherwise we're returned person ages over 18 so we run this it's true if we set it to 30 it should still be true because I'm over 30 years old if we set it to 40 it should be false because nobody's over perfect so it seems to be working all right we're gonna switch up our data a little bit and we're going to see how can we how can we count currencies of some value in an array so here I've got an array of orders just with an random ID and a status so I want to count how many times each status shows up and I want to end up with an object where you've got the status and how many times it occurred so we're gonna say result equals orders dot reduce but same idea and we are going to start it off as an empty object so we receive our accumulator and our order and what we are going to do is return and what we're gonna do is we're gonna take all of the counts we've found so far and we are going to update the current status that we're looking at so we'll do this dynamic key setting again so this would be ordered status and its value is going to be whatever it was before plus one now if it's the first time we see this thing it's gonna be whatever it is I think it's undefined if if that value is not there so what we're going to do is we are going to we are going to look it up and see if we have this status yet so back at ordered status or so if this is there's a value for this we'll get that value whether it be two or five or whatever or we're gonna start it off at zero meaning we're initializing it plus one just like that so take all of our counts so far we're gonna update the current status that we're looking at whether it be pending or canceled we're gonna take the existing value or initialize it to zero plus one bit of a mouthful but there we go so there's two pending there's one canceled then there's one shipped all right the next one we are going to look at is how to flatten an array so this is when often it's when you've got nested data structures like imagine a folder that can either have a file or another folder that contains other files maybe there's a folder that contains one file plus another folder with two files and you want to end up with an array of just file names so you want to flatten that out so what we're going to do is slightly differently than what we've seen before we are actually going to create a function called flatten and that's because it needs to be called recursively so we need to have like a named function that we can recursively call if we just sort of do this sort of anonymous arrow function there's no way I don't think to call itself but flatten will take the same signature so your accumulator and the current thing that you're iterating over so we'll call it the item so this is an item this is an item this is an item and I'm just going to start reducing this so we've got to result equal folders dot reduce our reducing function will be this flatten and we will initialize it to an empty rate so let's finish out the flatten functionality so item could be just in just an item a string or a number whatever or it could be an array so if this thing is an array so array dot is array what we need to do is basically recursively call itself so that it can flatten out all of its children so what we're going to do is return the item so far Plus item dot reduce so we've got like a reduce in a reduce where we are flattening it's calling the flatten function and our initial value is an empty array like that I think that's right anyways so if it's not an array what we can do is just take the existing items and add in the item here like that so if we run this there we go we've just flattened all of the folders out so we've gone we've grabbed the first one in that case it's not an array so it would have just take spread of the existing items which would be nothing because it's the first one and it would have added the item the second one would it would have done is it would have received this array here so it would have spread out the existing items which is index and then it would have spread out the result of reducing this array and then etc would have just keep going on and squishing things out calling itself recursively it is a little funky to get your head wrapped around this we can console dot log what the accumulator and the item looks like at each step so if we were to call this that does not help at all so the first time it's called it's empty and we've got index the second time it's called we've got our index in here and we've got the item being this but it just starts getting a little bit crazy because it's uh it's recursively calling itself so let's just actually you know what be an easier way let's see if this works what we are going to do is return the reduced version of that accept our initial value won't be an empty array it will be the accumulator full boy if this works it's gonna be fantastic let's run this get rid of the console that log clear this out oh shoot that's nice all right let me explain this again because I just simplified this I think so we are reducing the folders with this flattened function we're starting out as an empty array if the item that we're currently looking at happens to be an array we are going to have to reduce things further using the flatten function again except this time we're not starting out with an empty array we're starting out with whatever we're currently at as we're accumulating the items in this array if it's not an array what we can do is just sort of this looks very similar to when we were mapping spread out the the existing items and add on the new item that's cool all right the last thing we are going to do before we call this a day is we are going to try to critic create a simple version of reduce ourselves and I say simple because the real version of reduce allows for some additional complexities you don't have to pass an initial value and if you don't pass an initial value we'll use your first element of your array as the initial value I don't want to deal with that for this example so we'll just do a simple version we are going to call this thing reduce so like this and just to prove that it's working we will say reduce what are we going to be reducing we will pass in one two three our callback function will take our accumulator and our number and it will we're going to do a sum of it so we'll say accumulator plus the number and we will initialize this to zero so here I am passing in our array as the first parameter here in the way we are using it before reduce is a function of an array because it's been added to the prototype in this case I'm not I'm just doing a regular function where we're passing in the array that we want to reduce we've got our callback and we've got our initial value so what we can do is we can create create a variable to store our accumulator so accumulator we will initialize it to initial like that now we need to iterate over all of the items in the array so we'll use a for-loop for that so let i equals 0 i is less than the array length i plus plus and what we want to do as we iterate over each element in the array is update our accumulator to whatever the callback returns so we will call the callback and callback expects to receive the accumulator like that the current element that we're iterating over so this would be array at the index and the the actual callback function actually receives two additional arguments it receives the current index that you're on and I believe it receives the entire array let's just we'll leave them there they just aren't used at all cool so it's gonna loop through calling the callback for each element given the current accumulator the current item the index and the entire array and its result will replace whatever value accumulator hat so it's looping through and it's accumulating in the process once we get to the end we will return the final value that it encounters so if we run this we get 6 which is exactly what we wanted and we can even see if we add a console that log of the accumulator let's do it after like that we can see that it started out as one then it went to three and finally got to six which was our last value so that's a very simple without any checking at all that you actually did pass an array you did pass a callback function that your initial value is there that the arrays not there's a lot of checking we didn't do but this is a very simple way you can implement reduce yourself and one way that we're not going to get into but if anyone wants to try to submit a challenge is how could you stop this loop to return the result basically short circuited for example if you're trying to find a matching element if you find that element there's no point in continuing on and iterating over the remaining elements so it would be cool if you could basically abort this reduce I found the item I'm looking for here it is same with a few of them like any as soon as you find one thing that's true there's no point in continuously looping over the rest of the items you can basically aboard and return true it's all good it would that would make it a lot more efficient with all over 18 as soon as you find one that's false you no longer have to keep iterating because it's already proven false there's no point in going on same with find is what I'm talking about as soon as we find the person there's no point in continuing on it would be cool to basically just say abort here's the value get out of there I will I will commit to the source control my version of of the short circuit it will probably be up tomorrow if you're if you're viewing this on Friday Friday the what day is it the 24th of April so if you look at this on a 25th on the source control you should find my answer hope you enjoyed this hope you love reduce as much as I do have a good rest of the day take care bye
Info
Channel: Leigh Halliday
Views: 10,443
Rating: 4.9869065 out of 5
Keywords: javascript, tutorial, map, reduce, min, max, flatten, javascript reduce, javascript tutorial, javascript fundamentals
Id: NiLUGy1Mh4U
Channel Id: undefined
Length: 26min 57sec (1617 seconds)
Published: Fri Apr 24 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.