Skip to content

JavaScript array map(), find() and reduce() example

Ramesh Fadatare edited this page Aug 11, 2020 · 1 revision

The map() method creates a new array by applying a provided function on every element in the calling array.

The find() method returns the value of the first element that satisfies the provided function; otherwise undefined is returned.

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

JavaScript array map

The map() method creates a new array by applying a provided function on every element in the calling array.

const a1 = ['dog', 'tree', 'smart'];

const a2 = a1.map(e => e.toUpperCase());
console.log(a2);

We have an array of words. With the map() method, we apply the toUpperCase() method on each of the words.

This is the output:

[ 'DOG', 'TREE', 'SMART' ]

JavaScript array find

The find() method returns the value of the first element that satisfies the provided function; otherwise undefined is returned.

const nums = [2, -3, 4, 6, 1, 23, 9, 7];

const e1 = nums.find(e => e > 10);
console.log(e1);

In the example, we print the first value that is greater than 10.

This is the output:

23

JavaScript array reduction

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

const nums = [2, 3, 4, 5, 6, 7];

const res = nums.reduce((product, next) => product * next);

console.log(res);

This is the output:

5040
Clone this wiki locally