The Magic of the reduce Array Method

  Рет қаралды 22,969

All Things JavaScript, LLC

All Things JavaScript, LLC

Күн бұрын

Пікірлер: 82
@daniamsalem
@daniamsalem 4 жыл бұрын
Line 26 Explained: First off, thank you for the excellent video! I came to KZbin 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!
@alissonprimo
@alissonprimo 4 жыл бұрын
Thanks for the comment, now I’ve been able to understand 🙏🏻
@crystalchaung1576
@crystalchaung1576 4 жыл бұрын
Your explanation helped me. I read it and rewatched that problem, with necessary pauses.
@devanshupadhyay3984
@devanshupadhyay3984 3 жыл бұрын
underrated comment !! Nicely explained.
@jenso413
@jenso413 2 жыл бұрын
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!!
@haciendadad
@haciendadad 4 жыл бұрын
Finally, a great reduce demo!!
@gustavoconti3431
@gustavoconti3431 2 жыл бұрын
The second example with an object as the accumulator is just what I needed to get. Thank you for the explanation
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
Glad it helped!
@SabrinaMarkon
@SabrinaMarkon 5 жыл бұрын
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.
@mickwhyte4204
@mickwhyte4204 2 жыл бұрын
Really interesting approach to reduce, some techniques I would never have come across myself. Smart, clean, concise. Thanks!
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
Glad you enjoyed it!
@jetspray3
@jetspray3 3 жыл бұрын
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.
@moda4505
@moda4505 2 жыл бұрын
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!
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
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.
@moda4505
@moda4505 2 жыл бұрын
@@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!!
@haciendadad
@haciendadad 4 жыл бұрын
I gave this video a thumbs up after the first 10 seconds. His opening statement was right, and part of my frustration
@AshokKumar-dp5rv
@AshokKumar-dp5rv 3 жыл бұрын
Thank you! Great demo on reduce.
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
You're welcome!
@geld5220
@geld5220 3 жыл бұрын
wow - finally - an explanation that can be understood - thank you!
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
Glad it was helpful!
@capslock3250
@capslock3250 3 жыл бұрын
Max: Let maxNum = scores.reduce((a, b) => b > a? b : a); Min: Let minNum = scores.reduce((a, b) => b < a? b : a);
@zameeebasha
@zameeebasha 5 жыл бұрын
Very useful for taking reduce method to the next level. Cheers Steve
@GauravJoshi-Vlogs
@GauravJoshi-Vlogs 3 жыл бұрын
Really awesome video........really got to know how powerful the reduce function is..........thnX!!
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
You're welcome!
@shabnamnaaz4676
@shabnamnaaz4676 4 жыл бұрын
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 ?
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
Can you post the code that gave you an error?
@shabnamnaaz4676
@shabnamnaaz4676 4 жыл бұрын
@@AllThingsJavaScript var studentObj = students.reduce((acc, student) => { return { ...acc, student["userid"]: student //unexpected token '[' error } }, {})
@nhiemtran1430
@nhiemtran1430 5 жыл бұрын
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?
@AllThingsJavaScript
@AllThingsJavaScript 5 жыл бұрын
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
@marcocorapi5333
@marcocorapi5333 2 жыл бұрын
What happens if you do not use the computed value for person.userid?
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
You wouldn't get the value which is what we want for the property name.
@MecchaKakkoi
@MecchaKakkoi 5 жыл бұрын
Great examples. I really should use reduce a lot more!
@bladimirdoumerc15
@bladimirdoumerc15 5 жыл бұрын
Thanks a lot, men. Have a good one!
@t.a.4385
@t.a.4385 4 жыл бұрын
Thanks so much for the patience in teaching this. This really helped me understand the .reduce() function!!! Thanks!!!
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
Great to hear!
@rictolorio9062
@rictolorio9062 4 жыл бұрын
thanks a lot in this kind of tutorials, how about number data type in studentID, what code do i add to look an object?
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
Hi Ric! I'm not sure I understand the question. Can you explain what you are trying to do?
@rictolorio9062
@rictolorio9062 4 жыл бұрын
@@AllThingsJavaScript I want to use numeric in studentID instead of string, like 001, 002 and 003. Apologies, newly study javascript.
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
@@rictolorio9062 So you would just set the userId to a number. userid: 1
@justoverclock6083
@justoverclock6083 2 жыл бұрын
How if we want to show only object with the property = false?
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
you would check if property = false. If it does you return the acc with the additional information. If not you only return the acc.
@dapolcio3405
@dapolcio3405 3 жыл бұрын
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
@Luxcium
@Luxcium 5 жыл бұрын
I saw that you were using VSCODE at 7:16 yeah !!! 😄
@PrashantKumar-so1kj
@PrashantKumar-so1kj 4 жыл бұрын
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?
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
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
@PrashantKumar-so1kj 4 жыл бұрын
@@AllThingsJavaScript Thanks for clarifying Yes you understood correctly Can please tell me how to achieve that
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
@@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.
@rajatchaurasia2733
@rajatchaurasia2733 2 жыл бұрын
what if i want only name and passFail??
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
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.
@ChrisTian-ox5nr
@ChrisTian-ox5nr 3 жыл бұрын
such a great video! thank you!
@adietltesa
@adietltesa 4 жыл бұрын
Thanks a million!!!! very well explained, Finally I understood it!
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
Glad it helped!
@abyshekhar
@abyshekhar 3 жыл бұрын
Excellent!
@akshay__sood
@akshay__sood 4 жыл бұрын
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?
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
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?
@akshay__sood
@akshay__sood 4 жыл бұрын
@@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.
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
@@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?
@akshay__sood
@akshay__sood 4 жыл бұрын
@@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
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
@@akshay__soodFor this example yes, but not recommended.
@abelmurua6980
@abelmurua6980 3 жыл бұрын
Awesome! Thank you
@maenam4520
@maenam4520 10 ай бұрын
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.
@AllThingsJavaScript
@AllThingsJavaScript 9 ай бұрын
Yes, thanks for the comment.
@freddyescobar96
@freddyescobar96 3 жыл бұрын
what if I want my values return an array and not an object? is this possible? {stevenh: [values here] }
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
Yes, you would build an array instead of an object. Just add to the array each iteration.
@freddyescobar96
@freddyescobar96 3 жыл бұрын
@@AllThingsJavaScript thanks a lot master
@lokeshbajracharya5190
@lokeshbajracharya5190 4 жыл бұрын
brilliant! kudos!
@gamingstream1674
@gamingstream1674 4 жыл бұрын
let studentObj = Object.assign({}, ...students.map((ob)=> {return {[ob.a]:ob}})) This is Equal to the last reduce function but with Map .
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
Thanks for sharing. Many times map and reduce can be used interchangeably.
@Abhi_badale
@Abhi_badale 5 жыл бұрын
Awesome 😊
@zathkal4004
@zathkal4004 3 жыл бұрын
Super ... thanks sir (:
@sycoraxgriotsstudio5505
@sycoraxgriotsstudio5505 3 жыл бұрын
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);
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
I like this approach! Thanks for sharing.
@jaybhatt6775
@jaybhatt6775 3 жыл бұрын
are you god? maybe i found god ? i was breaking my head trying to figure out the exact problem u demonstrated in this video.
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
Glad it helped!
@neithanm
@neithanm 4 жыл бұрын
Great vid! Kill that 'var' thing though already :P
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
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.
@neithanm
@neithanm 4 жыл бұрын
@@AllThingsJavaScript I don't know of any case where you need to use var. Do you have a concrete example?
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
@@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.
@neithanm
@neithanm 4 жыл бұрын
@@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?
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
@@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.
@RameenFallschirmjager
@RameenFallschirmjager 4 жыл бұрын
horrifying bad, confusing examples.
@shabnamnaaz4676
@shabnamnaaz4676 4 жыл бұрын
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
Getting Comfortable with the ES5 Array Methods in JavaScript
30:56
All Things JavaScript, LLC
Рет қаралды 6 М.
The hardest JavaScript array method!
21:26
Coding in Public
Рет қаралды 2,9 М.
Beat Ronaldo, Win $1,000,000
22:45
MrBeast
Рет қаралды 158 МЛН
Что-что Мурсдей говорит? 💭 #симбочка #симба #мурсдей
00:19
Арыстанның айқасы, Тәуіржанның шайқасы!
25:51
QosLike / ҚосЛайк / Косылайық
Рет қаралды 700 М.
JavaScript Problem: Combining and Sorting Objects in an Array
21:39
All Things JavaScript, LLC
Рет қаралды 4,8 М.
Reduce: Mother of all Javascript Array Methods? (Part 5)
23:52
Jack Herrington
Рет қаралды 16 М.
Reduce: 10 Different Examples. JavaScript Fundamentals.
26:57
Leigh Halliday
Рет қаралды 29 М.
JavaScript Array Reduce Method Practice in 5 Minutes
8:02
James Q Quick
Рет қаралды 48 М.
Understanding JavaScript Callbacks
15:39
All Things JavaScript, LLC
Рет қаралды 115 М.
Master JavaScript Array Reduce Method In 10 Minutes
10:51
Colt Steele
Рет қаралды 7 М.
JavaScript Tip: 7 Ways to Iterate Over an Array
15:11
All Things JavaScript, LLC
Рет қаралды 9 М.
map, filter & reduce 🙏 Namaste JavaScript Ep. 19 🔥
37:42
Akshay Saini
Рет қаралды 945 М.
Beat Ronaldo, Win $1,000,000
22:45
MrBeast
Рет қаралды 158 МЛН