Sign in

JavaScript map(), filter(), reduce(), find(), forEach()methods

JavaScript Higher-Order functions allow functions that operate on other functions. These methods help to transforming, searching, and summing lists easier. These methods are are map(), filter(), reduce(), find(), forEach().

The map() method creates a new array with the results of calling a provided function on each element in this typed array.

const array = [2,3,6]
const newArray = array.map(e => e + 1)
console.log(newArray) // [3,4,7]

The filter() method creates a new typed array will all elements that pass the test implemented by the provided function.

const array = [2,3,6]
const newArray = array.filter(e => e > 3)
console.log(newArray) // [6]

The reduce() method applies a function against an accumulator and each value of the typed array (from left-to-right) has to reduce it to a single value.

const array = [2,3,6]
const newArray = array.reduce((sum,num) => sum + num, 0)
console.log(newArray) // 11

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. It will return undefined if no values satisfies the testing function.

const array = [-4, 11, 8,30, 32];const found = array.find(element => element > 10);console.log(found); // 11

The forEach() method executes a provided function once per array element.

//use forEach to count each item quantity
const items = ['pencil', 'book','pencil']
const count = {}
items.forEach(item => {
if (count[item]) {
count[item] +=1
return
}
count[item] = 1
})
console.log(count) // {pencil: 2, book: 1}

References:

JavaScript Arrays

A quick intro to Higher-Order Functions in JavaScript