Home > shorts > Coding reduce() function with JavaScript

Coding reduce() function with JavaScript


Coding reduce() function with JavaScript

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

const numbers = [1, 2, 3]
const reducer = (acc, cur) =>  acc + cur
const result = numbers.reduce(reducer, 0)

result // 6

Coding filter() function with plain JavaScript

const numbers = [1, 2, 3]
const reducer = (acc, cur) =>  acc + cur
const result = myReducer(reducer, 0, numbers)

function myReducer(reducer, initialValue, array){
    let acc = initialValue
    for(let i = 0; i < array.length; i++) {
        const cur = array[i]
        acc = reducer(acc, cur)
    }

    return acc
}

result // 6
© 2021, Andrew Losseff