Line 26 Explained: First off, thank you for the excellent video! I came to RUclips to understand `reduce()` because I knew arithmetic couldn't be all it was good for. Your video helped me understand there's a lot more going on under the hood. I also want to mention, the first time I saw you explain line 26 I too was confused. But after recalling how reduce's accumulator works in conjunction with the spread operator it all made sense. Here's my understanding of it: 1. On line 26, you're returning an object (that's why the return statement is bound by brackets). 2. The first return is going to spread the initialized accumulator (initialized on line 27) as an empty object. In other words, the first time the accumulator is spread there's nothing in it so this has no value. 3. Then you append the person.userid value as the key and the person object (Steven). That's why there's a comma after the spreaded accumulator value. So this first return is really just Steven's userid and his object. 4. Since this is a callback function, the process is repeated with the next person (Debbie). But this time the accumulator has accumulated the previous key and object of Steven. So Steven's key and his object is spread out and then Debbie's key and object are appended. This is returned and the callback function repeats once more. 5. The accumulator is again spread out with Steven and Debbie's key/object and then Max's key and object are appended. 6. All of this is returned as the value of studentObj. Genius!
ahh i've beent trying to wrap my head around this for hours, found this video and this comment in particular and it now almost makes sense. thank you!!
thank you for this more complex use of the reduce method it helped me grasp the value of it! Also was wondering if your're thinking of making a video about currying and partial application?
I haven't done one on those topics yet, but they are covered in my functional programming course if you are interested. If there is not currently a sale going on let me know and I can get a coupon code. www.udemy.com/course/functional-programming-in-javascript-a-practical-guide/?referralCode=B5E782141561F8233BFA
Great explanation, thanks!! Just one question: timestamp 12:00 you mention the computed value of the userid; and this is why to put the val.userid in brackets. Without brackets the function won't run, but what exactly is the computed value and why do we need the brackets to run this code? Thanks a million for your answer!
The computed value is just the value returned by using brackets. So brackets causes it to use the value stored in the variable instead of the text string, name of the variable.
@@AllThingsJavaScript Cannot thank you enough for your help in this and for all the insights you provide with your channel - thanks for your swift response, very much appreciated!!
this is undoubtedly the best tutorial on reduce method demo , thankyou so much one question I have : student["userid"] :student should also work r8? I remember you saying whatever is inside the brackets will get evaluated and if it finds a property with that string , it will evaluate to that properties value , then why did I get a error ?
Why there is [ ] in line 26 because you are declaring variable where JS doesn’t not accept (.) since that was destructuring and if you keep just person after …acc, person you will get the only the last obj from the main array because it assumes person as property so it will override its value and reflects the last obj. So [ ] is the solution to get the names or you can add one more parameter in the reduce callback function so access index and use it instead of names to include duplicated names if any in the final result.
I hope I'm understanding correctly, but it sounds like you want to return two things in a single pass. Those would all need to be part of an object, because reduce is only going to return one result.
@@PrashantKumar-so1kj In this tutorial we create one property and then the object is returned. Instead of just one, you would create two properties and return the object.
1. Does the return type and initial value have to be of same type? In 2nd case it was an object. 2. When an object is returned why ...acc is not returned as a part of the result?
The return type for the accumulator and the initial value should be the same type. I'm not sure I understand the second question, but whenever acc is returned it contains the previous data and all new data added to it. Does that help?
@@AllThingsJavaScript my first question was- The return type of the whole object that's returned from the function is an Object and the initial value we set which is an empty object is an Object..So they have to be of the same type? My second question was- The object which is returned from the function contains spread acc and the computed value, when you check in console for output why do we just see output of the computed property value and not acc.? I tried to elaborate.
@@akshay__sood First question: Yes that is a good practice, but technically we could have had the initial value as null which would have been a different type, but I would just keep them the same type. Second question: Actually the object that is returned from the function is an object. That object contains the property from acc (because we spread them out) and the userid. So a single object with that data in it. Did I address the question this time?
@@AllThingsJavaScript yes you did. 1. So initial value and return type from a function can be of different types? 2. Thank you... Il research more and get back to.you if any qnts
In the min and max score you`re using Math.min and Math.max, wich is I belive is alittle redundant becouse you can use Math.min(scores) But how about this short circuit evaluation application? // GET ARRAY OF MIN AND MAX SHORT CIRCUIT EVALUATION const minMax2 = numbers.reduce((acc, score) => [ acc[0] > score ? score : acc[0], acc[1] < score ? score : acc[1], ], [100, 0]); console.log(minMax2);
@@neithanm So the traditional module pattern: var MAIN = (function(nsp) {})(MAIN || {}); This structure will give you an error with let or const because the variable is not defined when the execution context is set up with let and const. That happens with var. You can get around it by using other patterns and ES modules, but if you want to use it, you have to use var.
@@AllThingsJavaScript Oh, ok. So like the revealing module pattern in an IIFE. Well, as you know, there's always someone who's had and fixed that problem before :) It's more like an antipattern: it's old and messy. Were you using it to avoid polluting the env or for what reason?
@@neithanm Yes, I use it as a revealing module pattern. There are ES6 modules now, but when you need pre ES6 code or a module in a browser and don't want to use the convoluted way for ES6 modules, it is there for you. I would not call it an anti-pattern.
go through all of his videos , I started from fundamentals playlist then arrays playlist . I understoood this , hope it helps . will definitely complete all his videos ,each one is worth it
Line 26 Explained: First off, thank you for the excellent video! I came to RUclips to understand `reduce()` because I knew arithmetic couldn't be all it was good for. Your video helped me understand there's a lot more going on under the hood.
I also want to mention, the first time I saw you explain line 26 I too was confused. But after recalling how reduce's accumulator works in conjunction with the spread operator it all made sense. Here's my understanding of it:
1. On line 26, you're returning an object (that's why the return statement is bound by brackets).
2. The first return is going to spread the initialized accumulator (initialized on line 27) as an empty object. In other words, the first time the accumulator is spread there's nothing in it so this has no value.
3. Then you append the person.userid value as the key and the person object (Steven). That's why there's a comma after the spreaded accumulator value. So this first return is really just Steven's userid and his object.
4. Since this is a callback function, the process is repeated with the next person (Debbie). But this time the accumulator has accumulated the previous key and object of Steven. So Steven's key and his object is spread out and then Debbie's key and object are appended. This is returned and the callback function repeats once more.
5. The accumulator is again spread out with Steven and Debbie's key/object and then Max's key and object are appended.
6. All of this is returned as the value of studentObj.
Genius!
Thanks for the comment, now I’ve been able to understand 🙏🏻
Your explanation helped me. I read it and rewatched that problem, with necessary pauses.
underrated comment !! Nicely explained.
ahh i've beent trying to wrap my head around this for hours, found this video and this comment in particular and it now almost makes sense. thank you!!
Finally, a great reduce demo!!
The second example with an object as the accumulator is just what I needed to get. Thank you for the explanation
Glad it helped!
Reduce is beyond cool! I love how you could have a huge list of users and just look them up by userid instead of having to know the array index.
I like how you break out of the basis of what were taught and illustrate how other things can be don't, so glad I subscribe to that channel.
Really interesting approach to reduce, some techniques I would never have come across myself. Smart, clean, concise. Thanks!
Glad you enjoyed it!
wow - finally - an explanation that can be understood - thank you!
Glad it was helpful!
I gave this video a thumbs up after the first 10 seconds. His opening statement was right, and part of my frustration
Very useful for taking reduce method to the next level. Cheers Steve
Thank you! Great demo on reduce.
You're welcome!
Really awesome video........really got to know how powerful the reduce function is..........thnX!!
You're welcome!
thank you for this more complex use of the reduce method it helped me grasp the value of it! Also was wondering if your're thinking of making a video about currying and partial application?
I haven't done one on those topics yet, but they are covered in my functional programming course if you are interested. If there is not currently a sale going on let me know and I can get a coupon code. www.udemy.com/course/functional-programming-in-javascript-a-practical-guide/?referralCode=B5E782141561F8233BFA
Great examples. I really should use reduce a lot more!
Thanks so much for the patience in teaching this. This really helped me understand the .reduce() function!!! Thanks!!!
Great to hear!
Thanks a lot, men. Have a good one!
Great explanation, thanks!! Just one question: timestamp 12:00 you mention the computed value of the userid; and this is why to put the val.userid in brackets. Without brackets the function won't run, but what exactly is the computed value and why do we need the brackets to run this code? Thanks a million for your answer!
The computed value is just the value returned by using brackets. So brackets causes it to use the value stored in the variable instead of the text string, name of the variable.
@@AllThingsJavaScript Cannot thank you enough for your help in this and for all the insights you provide with your channel - thanks for your swift response, very much appreciated!!
Thanks a million!!!! very well explained, Finally I understood it!
Glad it helped!
this is undoubtedly the best tutorial on reduce method demo , thankyou so much
one question I have :
student["userid"] :student should also work r8?
I remember you saying whatever is inside the brackets will get evaluated and if it finds a property with that string , it will evaluate to that properties value , then why did I get a error ?
Can you post the code that gave you an error?
@@AllThingsJavaScript
var studentObj = students.reduce((acc, student) => {
return {
...acc,
student["userid"]: student
//unexpected token '[' error
}
}, {})
such a great video! thank you!
Max:
Let maxNum = scores.reduce((a, b) => b > a? b : a);
Min:
Let minNum = scores.reduce((a, b) => b < a? b : a);
I saw that you were using VSCODE at 7:16 yeah !!! 😄
Why to make it so complicated. Isn't it much easier to code:
let minMax = [Math.min(...arr), Math.max(...arr)] - same result but much simpler
Excellent!
Why there is [ ] in line 26 because you are declaring variable where JS doesn’t not accept (.) since that was destructuring and if you keep just person after …acc, person you will get the only the last obj from the main array because it assumes person as property so it will override its value and reflects the last obj.
So [ ] is the solution to get the names or you can add one more parameter in the reduce callback function so access index and use it instead of names to include duplicated names if any in the final result.
Yes, thanks for the comment.
Awesome! Thank you
What happens if you do not use the computed value for person.userid?
You wouldn't get the value which is what we want for the property name.
brilliant! kudos!
How if we want to show only object with the property = false?
you would check if property = false. If it does you return the acc with the additional information. If not you only return the acc.
Super ... thanks sir (:
Awesome 😊
thanks a lot in this kind of tutorials, how about number data type in studentID, what code do i add to look an object?
Hi Ric! I'm not sure I understand the question. Can you explain what you are trying to do?
@@AllThingsJavaScript I want to use numeric in studentID instead of string, like 001, 002 and 003. Apologies, newly study javascript.
@@rictolorio9062 So you would just set the userId to a number. userid: 1
Can I use the reduce function to create a key value pair and the sum at a same time by calling the function just once?
I hope I'm understanding correctly, but it sounds like you want to return two things in a single pass. Those would all need to be part of an object, because reduce is only going to return one result.
@@AllThingsJavaScript
Thanks for clarifying
Yes you understood correctly
Can please tell me how to achieve that
@@PrashantKumar-so1kj In this tutorial we create one property and then the object is returned. Instead of just one, you would create two properties and return the object.
1. Does the return type and initial value have to be of same type? In 2nd case it was an object.
2. When an object is returned why ...acc is not returned as a part of the result?
The return type for the accumulator and the initial value should be the same type. I'm not sure I understand the second question, but whenever acc is returned it contains the previous data and all new data added to it. Does that help?
@@AllThingsJavaScript my first question was-
The return type of the whole object that's returned from the function is an Object and the initial value we set which is an empty object is an Object..So they have to be of the same type?
My second question was-
The object which is returned from the function contains spread acc and the computed value, when you check in console for output why do we just see output of the computed property value and not acc.?
I tried to elaborate.
@@akshay__sood First question: Yes that is a good practice, but technically we could have had the initial value as null which would have been a different type, but I would just keep them the same type.
Second question: Actually the object that is returned from the function is an object. That object contains the property from acc (because we spread them out) and the userid. So a single object with that data in it. Did I address the question this time?
@@AllThingsJavaScript yes you did.
1. So initial value and return type from a function can be of different types?
2. Thank you... Il research more and get back to.you if any qnts
@@akshay__soodFor this example yes, but not recommended.
what
if i want only name and passFail??
In the object that is returned you only need to place the data that you want. So just put the name and passFail in that object.
let studentObj = Object.assign({}, ...students.map((ob)=> {return {[ob.a]:ob}}))
This is Equal to the last reduce function but with Map .
Thanks for sharing. Many times map and reduce can be used interchangeably.
what if I want my values return an array and not an object? is this possible? {stevenh: [values here] }
Yes, you would build an array instead of an object. Just add to the array each iteration.
@@AllThingsJavaScript thanks a lot master
In the min and max score you`re using Math.min and Math.max, wich is I belive is alittle redundant becouse you can use Math.min(scores)
But how about this short circuit evaluation application?
// GET ARRAY OF MIN AND MAX SHORT CIRCUIT EVALUATION
const minMax2 = numbers.reduce((acc, score) =>
[
acc[0] > score ? score : acc[0],
acc[1] < score ? score : acc[1],
],
[100, 0]);
console.log(minMax2);
I like this approach! Thanks for sharing.
are you god? maybe i found god ? i was breaking my head trying to figure out the exact problem u demonstrated in this video.
Glad it helped!
Great vid! Kill that 'var' thing though already :P
Right! Use it sparingly, but there are times it will do what you can't do with let or const such as in the module pattern.
@@AllThingsJavaScript I don't know of any case where you need to use var. Do you have a concrete example?
@@neithanm So the traditional module pattern: var MAIN = (function(nsp) {})(MAIN || {}); This structure will give you an error with let or const because the variable is not defined when the execution context is set up with let and const. That happens with var. You can get around it by using other patterns and ES modules, but if you want to use it, you have to use var.
@@AllThingsJavaScript Oh, ok. So like the revealing module pattern in an IIFE. Well, as you know, there's always someone who's had and fixed that problem before :) It's more like an antipattern: it's old and messy. Were you using it to avoid polluting the env or for what reason?
@@neithanm Yes, I use it as a revealing module pattern. There are ES6 modules now, but when you need pre ES6 code or a module in a browser and don't want to use the convoluted way for ES6 modules, it is there for you. I would not call it an anti-pattern.
horrifying bad, confusing examples.
go through all of his videos , I started from fundamentals playlist then arrays playlist . I understoood this , hope it helps . will definitely complete all his videos ,each one is worth it