Map, Filter and Reduce

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

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> 
    <head>
        <title>Example using map() function</title>
        <script>
            let numbers = [1, 2, 3, 4] 
            let numbersSquared = numbers.map(number => number * number)

            console.log(`numbersSquared array is: ${numbersSquared}`)
        </script>
    </head>
    <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> 
    <head>
        <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>
    </head>
    <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> 
    <head>
        <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>
    </head>
    <body> 
        <p>View the console output in browser's Web DevTools (F12)</p>
    </body> 
</html> 
 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>