Ajay Yadav
Ajay Yadav

@ATechAjay

10 Tweets Jan 26, 2023
๐Ÿšฉ reduce( ) method in JavaScript
A Thread๐Ÿงต
๐Ÿ˜‰ Let's learn this topic through the "for" loop example.
โ—ช Suppose, we want to add all elements of the array using for loop.
โ—ช So, we can achieve this goal using the following method ๐Ÿ‘‡
๐Ÿ’ก Above snippet:
โ—ช The "total" is a global variable that is used to ๐˜€๐˜๐—ผ๐—ฟ๐—ฒ/๐—ฎ๐—ฐ๐—ฐ๐˜‚๐—บ๐˜‚๐—น๐—ฎ๐˜๐—ฒ/๐—ฐ๐—ผ๐—น๐—น๐—ฒ๐—ฐ๐˜ the resultant values after adding all items to the array.
โ—ช And it ๐—ถ๐—ป๐—ถ๐˜๐—ถ๐—ฎ๐—น๐—ฉ๐—ฎ๐—น๐˜‚๐—ฒ is 0, and in each iteration, we added an array item to the accumulator variable that is "total"
๐Ÿ”” But we can achieve this goal using the reduce( ) method in JavaScript.
๐Ÿญ reduce( )
โ—ช The reduce() method executes a reducer/shorter function on each element of the array.
โ—ช It returns a single value as a result and doesn't execute the function for an empty array element.
๐Ÿญ Syntax:
โ—ช total: It's an result of the previous function call, equal to the "InitialValue" the first time if provided.
โ—ช item: This is an individual(current) element of the array.
โ—ช index: It's a current index of the current element of the array.
โ—ช InitialValue: Starting value that is used to initialize the first time the callback function is called.
๐Ÿ’ก (Now compare the 1st example above with this syntax)
๐Ÿ’ก Example 1:
1st Iteration:
๐—ถ๐—ป๐—ถ๐˜๐—ถ๐—ฎ๐—น๐—ฉ๐—ฎ๐—น๐˜‚๐—ฒ = 0
total = 0
item = 10
2nd Iteration:
total = 10
item = 20
3rd Iteration:
total = 30
item = -30 , and so on...
โ—ช The resultant values will be stored in the "totalINR" variable.
๐Ÿ’ก Example 2:
โ“ Find the highest amount from the array.
โ—ช The resultant values will be stored in the "highAmount" variable.
โ—ช Here, the initial value is equal to the first element of the array which is 1025.
2nd iteration:
collect = 1025
item = 2640, and so on...
That's all for now, we will meet in the next thread๐Ÿ˜
๐Ÿ”” Follow Me @ATechAjay
For:
๐ŸŒ Web Development
โœจ JavaScript
๐Ÿ“ Writing Skill
๐Ÿ”ฅ Motivation
๐Ÿ’น Growth
โ›” But Not For Only Resources & Shitpost ๐Ÿ˜
Thank you so much for staying to the end of this thread๐Ÿ’š

Loading suggestions...