Created
October 11, 2022 02:10
-
-
Save danielnass/1e52abaff7c96a263a3e6870eed7fdd8 to your computer and use it in GitHub Desktop.
JavaScript Array Reduce from Scratch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1 - Create reduce function | |
function reduce(arr, fn, acc){ | |
// 5 - Iterate over each array value and reduce it with the accumulator into only one, assigning the result to the accumulator | |
for(value of arr){ | |
acc = fn(value, acc); | |
} | |
// 6 - Return the accumulator after iterates over each value of the array | |
return acc; | |
} | |
// 2 - Create an array to iterate into reduce | |
const myArr = [1,2,3]; | |
/ 3 - The callback function to reduce each array value and the accumulator into one | |
function add(a, b){ | |
return a + b; | |
} | |
// 4 - Execute the reduce function with myArr, add function and return it to countFullArray const | |
const countFullArray = reduce(myArr, add, 0); // 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment