Array map and reduce examples

by Carson Evans

HTML

<h1>Open the console</h1>

JavaScript

const array = [1, 2, 3 ,4]

/*

Map is used to create a new array who's items are dirrived from the items of
another array.

A callback is run on every item of an array, and returns a new array populated 
by the result of that callback. 

Example of using map to simply double all items of an array:

*/
const newArray = array.map(item => item * 2)



/*

Reduce is used to "reduce" the items of an array to a single value.

A callback is run on every item of the array. The callback should accept two
parameters: previousValue and currentValue. previousValue is the return value
of the previous call to the callback, and currentValue is the current item of
the array being reduced. For the first call of the callback 0 is passed as 
previousValue, or if the optional startingValue is passed to reduce after the
callback, that value is used.

Example of using reduce to sum all the items of an array together:

*/
const total = array.reduce((prevItem, currentItem) => prevItem + currentItem, 0)

/*

equivalent using plain for loops for both of the above exampels:

const newArray = []
for (let item of array) {
  newArray.push(item * 2)
}

let total = 0
for (let item of array) {
  total += item
}

*/

console.log(newArray)

console.log(total)