JavaScript Array Reduce

Поделиться
HTML-код
  • Опубликовано: 2 окт 2024
  • JavaScript Array Reduce
    🔥Get the COMPLETE course (83% OFF - LIMITED TIME ONLY): bit.ly/2KZea52
    Subscribe for more videos:
    / @programmingwithmosh
    Want to learn more from me? Check out my blog and courses:
    programmingwith...
    / programmingwithmosh
    / moshhamedani

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

  • @albatros280
    @albatros280 6 лет назад +455

    Finally... Somebody who explains reduce well. MDN documentation didn't help me.

  • @haroldcjennettiii
    @haroldcjennettiii 4 года назад +94

    Once again Mosh shows why he's one of the best coding teachers. You make things very clear, because you explain what EVERYTHING is, in laymen's terms. A lot of coding teachers forget they're teaching beginners.

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

    I love he teaches coding very clearly in a short amount of time. He's the best coding teacher.

    • @msh1830
      @msh1830 Год назад

      ruclips.net/video/a_Bfu1XWGmI/видео.html

  • @RetroRick1990
    @RetroRick1990 4 года назад +7

    Awesome , just understand what is the role of the "Accumulator" and the "Current Value" makes everything very clear. Thank man!

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

    I've explored every single line of MDN reference, but I didn't learn as much I could get from you. Appreciate that mate

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

    Boss more blessing to you, love from Nigeria. You just explained all MDN couldn't in minutes

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

    This video is posted a long time ago, but for the first time i understand reduce. Thanks Mosh!

  • @rpb4865
    @rpb4865 2 года назад +17

    Can anyone explain why for loop or foreach is "old way" and reduce is more "elegant way"?
    I find the"old way" more readable than the "elegant way"

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

      understand the elegant way and use the readable way if you want, after some months you will like to use the elegant way

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

      I also think the "old way" is better. The "elegant way" is limited to iteration of type y_n = f(y_{n-1}, x_n) where f is the callback function. There is this new movement in programming where people think old fashion for-loops are ugly code.

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

    Having it explained in video form is so much easier for me than reading it. Thank you!

    • @msh1830
      @msh1830 Год назад

      ruclips.net/video/a_Bfu1XWGmI/видео.html

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

    Thank you Mosh. I wish everyone can explain things as clearly as you.

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

    Thank you for explaining this right! No one seems to explain the first callback value as the accumulator but yet as the previous value.

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

    Thank you dude, this is incredible. I wasn't understanding this before watching your video, thank you.

  • @zdargahi
    @zdargahi 5 лет назад +68

    It would be great if you explain how the accumulation can be an array or object, and how when instead of chaining map and filter we can use reduce. I guess it's in the complete course.

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

      If you were using an array, you could return an array in the reduce, and spread the accumulator. Then add any new value after. Example:
      nums = [1,2,3,4,5]
      const doubledNums = nums.reduce( (acc, num) => [...acc, num*2], [ ])
      console.log(doubledNums) // [2,4,6,8,10]
      Obviosuly a .map could do the same thing but there are more complex examples where it is useful.

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

      @@liamwelsh5565 Hi, I'm very new to coding, may I know why did you add the "..." before acc? I'm not really sure what it does here

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

      @@Xetron1978 … is the spread operator. If you have an array, let’s call x and want to make a new array, let’s call y, that has all the values of x, you can spread x into y.
      Example:
      Const x = [1,2,3]
      Const y = […x]
      Console.log(y)
      // [1,2,3]
      You can also spread objects into objects

  • @j.k.ravshanovich
    @j.k.ravshanovich 4 года назад

    Explained better than MDN. Good job!

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

    This explanation is way better than the documentation.

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

    Mosh, thank you so much! You broke this down into a very easy to understand way.

  • @jame_sta
    @jame_sta 6 лет назад +1

    You're the BEST Instructor I've ever come across +ProgrammingwithMosh
    *sheds a tear* LOL :D -- I can't wait for more JS videos!!!!!

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

    Excellent explanation of reduce function.

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

    The best teacher so far

  • @martinlipinski1403
    @martinlipinski1403 Год назад

    You are a king in easy explaining

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

    He the best teacher on the internet

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

    very easy to understand by good explanation

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

    Thank you for the good explanation and help.

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

    thanks buddy for making concept clear

  • @harwinderthakur9708
    @harwinderthakur9708 4 года назад +8

    I spent 20 minutes on mdn understanding all this. I got more confused there.Thanks man

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

    Very important topic explained easily.

  • @moinkhan-xd6pe
    @moinkhan-xd6pe Год назад

    best coding teacher :)

  • @Phoenix24Leas
    @Phoenix24Leas 4 года назад +6

    This is nice but it'd be great if there was something on how to use reduce when making new objects/arrays

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

    Very helpfull and clear as well in the explaination MDN was making me crazy. Thanks mosh! :)

  • @beedev5197
    @beedev5197 5 лет назад

    It was really clear explanation. Thanks a lot Mosh!

  • @whynologin
    @whynologin 5 лет назад

    Thank you sir for explaining this so clearly.

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

    Thank you was having trouble understanding it

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

    Nice class, thanks for this content!

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

    Nice explanation, thanks 😊

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

    Wow, so clear. Thanks, Mosh!!

  • @MelanieTv
    @MelanieTv 5 лет назад +9

    No entiendo bien el ingles, y entendí el uso del Reduce super bien :0, u eso creo, jaja Muchas gracias!

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

      jajaj mosh es muy bien!

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

    actually, it must be accumulator += currentValue but just + works here maybe because of reduce method is holding the current value in memory for every iteration.

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

    Thank you very much for this video! It helps a lot and the examples make it clear :)

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

    Very well explained, thank you!

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

    thanks for great explanation!

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

    Amazing explanation dude !!! I actually do prefer to use map, filter, sort and reduce function as i have read on a paper that imperative languages as Javascript, the high order functions works really faster than looping or with recursion. What do you think about that, it is like that ? Greetings and thanks again !

  • @golden-dragon1442
    @golden-dragon1442 3 года назад +1

    hi Mosh thank you for the video. one thing i didnt understand was the second argument (0), i understand that it represents the number 1 (being the first on teh array) but what if thaht number is 3 or 10 what will happen when the code logs?

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

    excellent tutorial but i think the for loop still looks cleaner

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

    finally, I can totally understand the reduce method thanks to you, appreciate your channel

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

    well explained, thanks.

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

    Thank you so much. This was such a huge help!

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

    That's exactly what I needed. Thanks.

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

    Really helpful man....

  • @toantruong9203
    @toantruong9203 5 лет назад

    Easy and simple, thank you!

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

    very clear thank you so much

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

    awasom very good explanation

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

    great explanation Mosh..
    [...Array(1000)].reduce((acc, elem) => {
    return acc + 'Thanks Mosh ';
    }, ['Great Explanation ']);

  • @shadab8798
    @shadab8798 5 лет назад

    can you give some other examples of reduce use cases.

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

    now it 2020 but it still good thank you mann for this video !

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

    Amazingly clear!! Functional Programming is the best ❤️

    • @msh1830
      @msh1830 Год назад

      ruclips.net/video/a_Bfu1XWGmI/видео.html

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

    You Are Great..........................

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

    Hadn't got used to that reduce method and was struggling for a while, only took me a minute of your explanation to spark a lightbulb in my head and I felt relieved. Thank you.

    • @msh1830
      @msh1830 Год назад

      ruclips.net/video/a_Bfu1XWGmI/видео.html

  • @Chief_Sir_E.C.O._Nwuju
    @Chief_Sir_E.C.O._Nwuju Год назад +1

    Thank you so much brother,your explanation was very simple and clear

  • @LucasGuanes
    @LucasGuanes Год назад

    6:39 I felt that

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

    Thank you, Mosh. I found this very helpful for grasping the concept of reduce().

  • @RaylinAquino_
    @RaylinAquino_ 5 лет назад

    So useful many thanks

  • @miiMarit207
    @miiMarit207 7 дней назад

    Now I finally understand what is really happening with the reduce method.

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

    How am I only finding your tutorials now. You explain so well. I'm taking you with me for the rest of my Java script journey.

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

    How did the function taked "numbers" const?

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

    Finally ... some who explain reduce well .Thanks

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

    Hi Mosh, great video! Could you make a similar one explaining array sort?

  • @sarapoli5786
    @sarapoli5786 Год назад

    Omg I wouldn't learn it without this video. Still I think for loop is easier ;) I think reduce is fancy way of coding :D I don't like it but that's the way you see people code in real job :D

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

    Thank you for making js clear and simple to understand

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

    But why the second argument in numbers.reduce() (zero) goes to "accumulator"?

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

      it is the implementation of the function reduce(). A implementation could be like that:
      const reduce = function(iterable, reduceFn, accumulator){
      for(let i of iterable){
      accumulator = reduceFn(accumulator, i)
      }
      return accumulator
      }

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

      ? each time we add to the accumulator.
      the current value starts at 0
      mosh didn't explain this part but you can change the starting value with a last argument after teh callback.. in the exmple below the starting value and starting accumulator value would be 50.
      const final=numbers.reduce((accumulator, current val)=>{
      return accumulator+current val
      }, 50);
      we start by adding the first number in the array to 50(or the first current value we are working with) then if that result was 52... then the accumulator is 52, then the current value moves on to the next index number in the array and keeps going until it adds each value in the array together onto the accumulator
      basically the current value is the current value in the array we are currently working with. each array method does whatver the callback says to do on EACH value in the array. the current value in moshes example becomes 0 at one point because we add -1 to 1... which is 0
      hope this helped?

    • @mrswolls
      @mrswolls День назад

      It’s an optional argument specific to reduce methods that instruct the accumulator as to which element to begin. If no initial value is provided (the number you’re speaking of), the first element of the array is used as the accumulator’s starting value, and the iteration starts from the second element.

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

    this was fucking awesome! I felt guilty for not subscribing :D

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

    This is by far the clearest explanation I've seen on the reduce method so far.. Thanks a lot Mr Mosh..

  • @pranjalruhela1103
    @pranjalruhela1103 19 дней назад

    Accumulator, current value (through iterations) and initial value

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

    Thank you!

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

    Hi , Anyone knowwhy when i use:
    const numbers = [1, -1, 2, 3];
    let sum = 0;
    for (let n in numbers)
    sum += n;
    console.log("sum: " + sum);
    getting - sum: 00123

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

    Cleanest explanation I've seen so far. You just earned yourself a sub.

  • @ataimakashov2097
    @ataimakashov2097 5 лет назад

    But why 'minus' operator in reduce function results in -3, when it's obviously -5? (when not specifying index)

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

    mosh didn't explain this part but you can change the starting value with a last argument after the callback.. he kind of explained it but didn't fully lol... in the example below the starting value and thus the starting accumulator value would be 50.
    const final=numbers.reduce((accumulator, current val)=>{
    return accumulator+current val
    }, 50);

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

    Looking at the comments below people have spent ages trying to understand the reduce function. Why? Cos just like everything in Javascript its BS! :6:43 Mosh talks about the old way - using For loops. Well at least for loops are self evidently obvious! If i'm debugging code I don't want to spend an eternity trying to understand symbols that have no apparent meaning or reference!

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

    hay quá, cảm ơn bạn

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

    Wow! Explained in a super easy way. Thank you.

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

    THANK YOU

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

    Nice explanation of the Reduce Method of arrays. Thanks, Mosh
    {2021-08-14}

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

    Took me a while to get reduce even after learning all the other iteration methods. Thank you!

  • @ryansatriayudha
    @ryansatriayudha 11 месяцев назад

    This is very clear and simple explanation!! Thank you very much 😊

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

    Lovely explaination and lovely Mosh.
    We Love You Mosh, From Iran.

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

    Thank u for the great explanation
    let num = numbers.reduce((a,c) => a+=c ,2)

  • @adexmokson7185
    @adexmokson7185 Год назад

    This is just the simplest of reduce function it is far more complicated than this. It is the most complicated array method and using it for sum is not really the objective.

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

    Does anyone know if we can change the function to where it SUBTRACTS and accumulator and aggregator?
    Also, why the need to write out an entire function if a method is supposed to be a shortcut for this?

  • @EnricMartin1987
    @EnricMartin1987 Год назад

    Thank you Mosh. This is one of the best explanations about how to use reduce, that I could find on RUclips.

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

    The way this is presented seems to suggest that the reduce method is only used to sum all the values in an array. You have an accumulator and a current value. However, it's my understanding you can do other calculations with reduce to get at a single value. How would you find the maximum number in an array of numbers, for example, using reduce? What is the function of the accumulator and current value in that case? I find this demo very clear in how it works with summing all the values in an array, but it really doesn't show how reduce works in the real world, and I'm afraid it's a little misleading.

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

    Thank really. I was making a project. I am adding tips of bills as % to a calculation machine and i need to sum all tips and print. At the end i succeeded by looking to your tutorial. Thanks so much.

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

    Excellent and simplified. Is this method not called object deconstruction?

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

    thank you for explaning the basic concepts very clear...best explanation

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

    What if you had multiple objects with multiple properties nested inside an array and you wanted to use .reduce on the same property for each object? Just need to nest everything properly?

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

    interesting ... i like the way u teaching explaining...thank u so much....and keep it up....

  • @mavs4life248
    @mavs4life248 6 месяцев назад

    Thank you for breaking this down in detail. Very easy to understand.

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

    Your explanation was amazing! By the way, which VS Code theme is that?

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

    Best... Thank you sir...love from india.♥️

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

    actually, I like old way much better. javascript simply sucks.

  •  3 года назад

    Thanks a lot! Very good explaination ;)