📖 JavaScript Array Methods map, filter, reduce

Array methods like map, filter, and reduce are fundamental in JavaScript programming for processing and transforming array data. Understanding these methods is crucial for efficient data manipulation and functional programming.

Overview of JavaScript Arrays

JavaScript arrays are versatile and essential data structures that store multiple values in a single variable. Arrays can hold different types of data, such as numbers, strings, objects, and even other arrays. Here are some key points about arrays:

Creation
Arrays can be created using square brackets [] or the Array constructor.
Indexing
Elements in an array are accessed using zero-based indexing.
Properties and Methods
Arrays come with a variety of built-in properties and methods to manipulate and traverse their elements.

// Creating an array
let fruits = ['Apple', 'Banana', 'Cherry'];

// Accessing elements
console.log(fruits[0]); // Output: Apple

// Adding an element
fruits.push('Date');
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry', 'Date']

// Removing the last element
fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
        

Task

Learn how to use the map, filter, and reduce methods to process arrays. These methods allow you to perform common data manipulation tasks with clean and readable code.

map
Creates a new array by applying a provided function to each element of the original array.
filter
Creates a new array with all elements that pass the test implemented by the provided function.
reduce
Executes a reducer function on each element of the array, resulting in a single output value.

Coding Examples


// Using map to double the values in an array
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8]

// Using filter to get even numbers from an array
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]

// Using reduce to sum the values in an array
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Output: 10
        

Putting It Into Action

Create an HTML file and include the following script to see these methods in action. This script will demonstrate how map, filter, and reduce can be used to process array data.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Methods Example</title>
</head>
<body>
    <script>
        // Using map to double the values in an array
        const numbers = [1, 2, 3, 4];
        const doubled = numbers.map(num => num * 2);
        console.log(doubled); // Output: [2, 4, 6, 8]

        // Using filter to get even numbers from an array
        const evenNumbers = numbers.filter(num => num % 2 === 0);
        console.log(evenNumbers); // Output: [2, 4, 6]

        // Using reduce to sum the values in an array
        const sum = numbers.reduce((total, num) => total + num, 0);
        console.log(sum); // Output: 10
    </script>
</body>
</html>
        

Challenge

Create an array of objects representing people with properties name and age. Use map to create an array of names, filter to create an array of people older than 18, and reduce to calculate the average age.

In order to check your learning, you should attempt to create a solution before revealing the provided solution below.

Challenge Solution


const people = [
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 17 },
    { name: 'Charlie', age: 22 },
    { name: 'David', age: 15 }
];

// Using map to create an array of names
const names = people.map(person => person.name);
console.log(names); // Output: ['Alice', 'Bob', 'Charlie', 'David']

// Using filter to create an array of people older than 18
const adults = people.filter(person => person.age > 18);
console.log(adults); // Output: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 22 }]

// Using reduce to calculate the average age
const totalAge = people.reduce((sum, person) => sum + person.age, 0);
const averageAge = totalAge / people.length;
console.log(averageAge); // Output: 19.75
                        

References