umma.dev

Map/Filter/Reduce Arrays

This post outlines how .map(), .filter() and .reduce() differ, with examples for each method.

.map()

Array.prototype.map()

Mapping over an array creates a new array with the results of return in the function.

// syntax
let newArr = arr.map(function callbackName(
    currentValue[index[array]] {
        // return condition
    }, [args]
))

An example of .map()

let arr = [1, 2, 3, 4]

const newArr = arr.map(x => x+1)

.filter()

Array.prototype.filter()

This method creates a new array with data that passes the conditions in the return function.

// syntax
let newArr = arr.filter(callback(
    element[index[array]]
), [args])

An example of .filter()

const valueCondition = (val) => {
    return val >=10
}
let arr = [100, 33, 5, 72, 9]
let filterArr = arr.filter(valueCondition)

.reduce()

Array.prototype.reduce()

A provided reducer function is executed on each element of the array, with an output of a single value.

// syntax
arr.reduce(callback(
    accumlator,
        current[index[array]]
)initialValue)

An example of .reduce()

const arr = [1, 4, 5, 6]
const reducer = (accumulator, currentValue) => accumulator + currentValue
console.log(arr.reduce(reducer))