The Magic of the reduce Array Method

Поделиться
HTML-код
  • Опубликовано: 25 окт 2024

Комментарии • 82

  • @daniamsalem
    @daniamsalem 4 года назад +24

    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!

    • @alissonprimo
      @alissonprimo 3 года назад +1

      Thanks for the comment, now I’ve been able to understand 🙏🏻

    • @crystalchaung1576
      @crystalchaung1576 3 года назад +1

      Your explanation helped me. I read it and rewatched that problem, with necessary pauses.

    • @devanshupadhyay3984
      @devanshupadhyay3984 3 года назад +1

      underrated comment !! Nicely explained.

    • @jenso413
      @jenso413 2 года назад +1

      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 года назад +7

    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

  • @SabrinaMarkon
    @SabrinaMarkon 5 лет назад +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.

  • @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.

  • @mickwhyte4204
    @mickwhyte4204 2 года назад

    Really interesting approach to reduce, some techniques I would never have come across myself. Smart, clean, concise. Thanks!

  • @geld5220
    @geld5220 2 года назад

    wow - finally - an explanation that can be understood - thank you!

  • @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

  • @zameeebasha
    @zameeebasha 5 лет назад +3

    Very useful for taking reduce method to the next level. Cheers Steve

  • @AshokKumar-dp5rv
    @AshokKumar-dp5rv 3 года назад

    Thank you! Great demo on reduce.

  • @GauravJoshi-Vlogs
    @GauravJoshi-Vlogs 3 года назад

    Really awesome video........really got to know how powerful the reduce function is..........thnX!!

  • @nhiemtran1430
    @nhiemtran1430 4 года назад +1

    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

  • @MecchaKakkoi
    @MecchaKakkoi 5 лет назад +1

    Great examples. I really should use reduce a lot more!

  • @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!!!

  • @bladimirdoumerc15
    @bladimirdoumerc15 4 года назад +2

    Thanks a lot, men. Have a good one!

  • @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 года назад +1

      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 года назад +1

      @@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!!

  • @adietltesa
    @adietltesa 4 года назад

    Thanks a million!!!! very well explained, Finally I understood it!

  • @shabnamnaaz4676
    @shabnamnaaz4676 4 года назад +1

    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
      }
      }, {})

  • @ChrisTian-ox5nr
    @ChrisTian-ox5nr 3 года назад

    such a great video! thank you!

  • @capslock3250
    @capslock3250 3 года назад +1

    Max:
    Let maxNum = scores.reduce((a, b) => b > a? b : a);
    Min:
    Let minNum = scores.reduce((a, b) => b < a? b : a);

  • @Luxcium
    @Luxcium 5 лет назад +2

    I saw that you were using VSCODE at 7:16 yeah !!! 😄

  • @dapolcio3405
    @dapolcio3405 3 года назад +2

    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

  • @abyshekhar
    @abyshekhar 3 года назад

    Excellent!

  • @maenam4520
    @maenam4520 7 месяцев назад

    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.

  • @abelmurua6980
    @abelmurua6980 3 года назад

    Awesome! Thank you

  • @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.

  • @lokeshbajracharya5190
    @lokeshbajracharya5190 4 года назад

    brilliant! kudos!

  • @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.

  • @zathkal4004
    @zathkal4004 3 года назад

    Super ... thanks sir (:

  • @Abhi_badale
    @Abhi_badale 5 лет назад +1

    Awesome 😊

  • @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

  • @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 года назад +1

      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 года назад +1

      @@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.

  • @akshay__sood
    @akshay__sood 4 года назад +1

    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 года назад +1

      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 года назад +1

      @@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 года назад +1

      @@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.

  • @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.

  • @gamingstream1674
    @gamingstream1674 4 года назад +1

    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 года назад +2

      Thanks for sharing. Many times map and reduce can be used interchangeably.

  • @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 года назад +1

      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

  • @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);

  • @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.

  • @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