Skip to content

Instantly share code, notes, and snippets.

@danielnass
Created October 11, 2022 02:10
Show Gist options
  • Save danielnass/1e52abaff7c96a263a3e6870eed7fdd8 to your computer and use it in GitHub Desktop.
Save danielnass/1e52abaff7c96a263a3e6870eed7fdd8 to your computer and use it in GitHub Desktop.
JavaScript Array Reduce from Scratch
// 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