# Map, Filter and Reduce

The map(), filter() and reduce() functions operate on arrays (including arrays of objects).

• All of these functions will iterate through all of the elements of an array.
• All of these functions is non-mutating (does not change the data in the original array).

## map()

The map() function creates a new array that contains the results of calling a provided function on every element in the calling array. We should use map() in place of for-loops.

map() applied to an array (Run Example)

```<!DOCTYPE html>
<html>
<title>Example using map() function</title>
<script>
let numbers = [1, 2, 3, 4]
let numbersSquared = numbers.map(number => number * number)

</script>
<body>
<p>View the console output in browser's Web DevTools (F12)</p>
</body>
</html> ```

Implement the code above using a for-loop, as shown here. Compare the two approaches and discuss the benefits of using map() instead of a for-loop

## filter()

The filter() function creates a new array that contains all elements from the original array that pass the logical test implemented by the provided function. In the example below, the logical test is number % 2 === 1

filter() applied to an array (Run Example)

```<!DOCTYPE html>
<html>
<title>Example using filter() function</title>
<script>
let numbers = [1, 3, 6, 8, 11]
let oddNumbers = numbers.filter(number => number % 2 === 1)

console.log(`oddNumbers array is: \${oddNumbers}`)
</script>
<body>
<p>View the console output in browser's Web DevTools (F12)</p>
</body>
</html> ```

## reduce()

The reduce() function reduces an array to a single value. This value is the result of applying a given function against an accumulator and each element in the array (from left to right). The accumulator must be set with an initial value.

In the examples below, the variable total is the accumulator. The accumulator has been initialised to 0.

reduce() applied to an array (Run Example)

```<!DOCTYPE html>
<html>
<title>Example using reduce() function</title>
<script>
let numbers = [1, 3, 6, 8, 11]
let total = numbers.reduce((total, number) => total + number, 0)

console.log(`total is: \${total}`)
</script>