The Magic of the reduce Array Method

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

All Things JavaScript, LLC

All Things JavaScript, LLC

Күн бұрын

Many times the JavaScript reduce method is limited because we are not creative enough with it. Reduce can do so much and in this tutorial we look at a couple of examples in order to show its possibilities.
Would you like to help keep this channel going?
/ allthingsjavascript
Access to EVERY course (get 2 months free): www.skillshare.com/r/profile/...
Courses offered on Udemy at a discount (access from my site): allthingsjavascript.com/course...
Article: jrsinclair.com/articles/2019/...
Tutorials referred to in this video:
Reduce Intro and other array methods: • Getting Comfortable wi...
Spread Operator: • Using the JavaScript S...
Arrow Functions: • Arrow Functions
For more resources on JavaScript:
www.allthingsjavascript.com
#javascript #AllThingsJavaScriptLLC

Пікірлер: 84
@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 3 жыл бұрын
Thanks for the comment, now I’ve been able to understand 🙏🏻
@crystalchaung1576
@crystalchaung1576 3 жыл бұрын
Your explanation helped me. I read it and rewatched that problem, with necessary pauses.
@devanshupadhyay3984
@devanshupadhyay3984 2 жыл бұрын
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!!
@SabrinaMarkon
@SabrinaMarkon 4 жыл бұрын
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.
@haciendadad
@haciendadad 4 жыл бұрын
Finally, a great reduce demo!!
@zameeebasha
@zameeebasha 4 жыл бұрын
Very useful for taking reduce method to the next level. Cheers Steve
@bladimirdoumerc15
@bladimirdoumerc15 4 жыл бұрын
Thanks a lot, men. Have a good one!
@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.
@MecchaKakkoi
@MecchaKakkoi 4 жыл бұрын
Great examples. I really should use reduce a lot more!
@AshokKumar-dp5rv
@AshokKumar-dp5rv 2 жыл бұрын
Thank you! Great demo on reduce.
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
You're welcome!
@ChrisTian-ox5nr
@ChrisTian-ox5nr 2 жыл бұрын
such a great video! thank you!
@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!
@mickwhyte4204
@mickwhyte4204 Жыл бұрын
Really interesting approach to reduce, some techniques I would never have come across myself. Smart, clean, concise. Thanks!
@AllThingsJavaScript
@AllThingsJavaScript Жыл бұрын
Glad you enjoyed it!
@adietltesa
@adietltesa 4 жыл бұрын
Thanks a million!!!! very well explained, Finally I understood it!
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
Glad it helped!
@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!
@geld5220
@geld5220 2 жыл бұрын
wow - finally - an explanation that can be understood - thank you!
@AllThingsJavaScript
@AllThingsJavaScript 2 жыл бұрын
Glad it was helpful!
@abelmurua6980
@abelmurua6980 3 жыл бұрын
Awesome! Thank you
@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!
@lokeshbajracharya5190
@lokeshbajracharya5190 3 жыл бұрын
brilliant! kudos!
@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
@nhiemtran1430
@nhiemtran1430 4 жыл бұрын
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 4 жыл бұрын
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
@abyshekhar
@abyshekhar 2 жыл бұрын
Excellent!
@Luxcium
@Luxcium 4 жыл бұрын
I saw that you were using VSCODE at 7:16 yeah !!! 😄
@Ashiq619
@Ashiq619 4 жыл бұрын
Awesome 😊
@zathkal4004
@zathkal4004 3 жыл бұрын
Super ... thanks sir (:
@shabnamnaaz4676
@shabnamnaaz4676 3 жыл бұрын
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 3 жыл бұрын
Can you post the code that gave you an error?
@shabnamnaaz4676
@shabnamnaaz4676 3 жыл бұрын
@@AllThingsJavaScript var studentObj = students.reduce((acc, student) => { return { ...acc, student["userid"]: student //unexpected token '[' error } }, {})
@rictolorio9062
@rictolorio9062 3 жыл бұрын
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 3 жыл бұрын
Hi Ric! I'm not sure I understand the question. Can you explain what you are trying to do?
@rictolorio9062
@rictolorio9062 3 жыл бұрын
@@AllThingsJavaScript I want to use numeric in studentID instead of string, like 001, 002 and 003. Apologies, newly study javascript.
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
@@rictolorio9062 So you would just set the userId to a number. userid: 1
@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);
@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
@moda4505
@moda4505 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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!!
@PrashantKumar-so1kj
@PrashantKumar-so1kj 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
@@AllThingsJavaScript Thanks for clarifying Yes you understood correctly Can please tell me how to achieve that
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
@@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.
@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.
@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.
@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.
@maenam4520
@maenam4520 3 ай бұрын
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 3 ай бұрын
Yes, thanks for the comment.
@rajatchaurasia2733
@rajatchaurasia2733 Жыл бұрын
what if i want only name and passFail??
@AllThingsJavaScript
@AllThingsJavaScript Жыл бұрын
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.
@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
@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 3 жыл бұрын
Great vid! Kill that 'var' thing though already :P
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
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 3 жыл бұрын
@@AllThingsJavaScript I don't know of any case where you need to use var. Do you have a concrete example?
@AllThingsJavaScript
@AllThingsJavaScript 3 жыл бұрын
@@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 3 жыл бұрын
@@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 3 жыл бұрын
@@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.
@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.
@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.
@kendall.jenner
@kendall.jenner 4 жыл бұрын
Still unclear on line 26 :/
@AllThingsJavaScript
@AllThingsJavaScript 4 жыл бұрын
If you need to review the spread operator, here is a tutorial: kzbin.info/www/bejne/q5jaZGWPpdetoNk
@RameenFallschirmjager
@RameenFallschirmjager 4 жыл бұрын
horrifying bad, confusing examples.
@shabnamnaaz4676
@shabnamnaaz4676 3 жыл бұрын
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 М.
JavaScript Tip: 7 Ways to Iterate Over an Array
15:11
All Things JavaScript, LLC
Рет қаралды 9 М.
Would you like a delicious big mooncake? #shorts#Mooncake #China #Chinesefood
00:30
How to bring sweets anywhere 😋🍰🍫
00:32
TooTool
Рет қаралды 55 МЛН
World’s Deadliest Obstacle Course!
28:25
MrBeast
Рет қаралды 92 МЛН
Learn the JavaScript Reduce function in 18 minutes (for beginners)
18:23
JavaScript reduce() method in 5 minutes! ♻
5:31
Bro Code
Рет қаралды 18 М.
The hardest JavaScript array method!
21:26
Coding in Public
Рет қаралды 2,8 М.
Master JavaScript Array Reduce Method In 10 Minutes
10:51
Colt Steele
Рет қаралды 7 М.
Understanding JavaScript Callbacks
15:39
All Things JavaScript, LLC
Рет қаралды 114 М.
Filter context in DAX explained visually
24:40
SQLBI
Рет қаралды 8 М.
16.7: Array Functions: reduce() - Topics of JavaScript/ES6
14:40
The Coding Train
Рет қаралды 132 М.
Reduce: 10 Different Examples. JavaScript Fundamentals.
26:57
Leigh Halliday
Рет қаралды 28 М.
JavaScript Problem: Combining and Sorting Objects in an Array
21:39
All Things JavaScript, LLC
Рет қаралды 4,6 М.
Would you like a delicious big mooncake? #shorts#Mooncake #China #Chinesefood
00:30