In JavaScript, map(), filter(), and reduce() are used to process and manipulate arrays of data. They are functional programming methods that can be used to transform, filter, and aggregate data in a declarative and concise way.

Here’s a brief overview of when to use each method.

Transforming an array using map()

map() is used to transform an array by applying a function to each element and returning a new array of the same length. Use map() when you need to apply the same operation to every element in an array and generate a new array with the transformed values.

Syntax of map()

const newArray = originalArray.map((currentValue, index, array) => {
  // return the new value of the current element
});

Example of map()

The following code creates a new array that contains the square of each number in the original array:

const numbers = [1, 2, 3, 4, 5];

const squares = numbers.map(n => n * n);

console.log(squares); // [1, 4, 9, 16, 25]

Filtering an array using filter()

filter() is used to create a new array containing only the elements that pass a given test. Use filter() when you need to select a subset of the elements in an array based on some condition and generate a new array with only the selected elements.

Syntax of filter()

const newArray = originalArray.filter((currentValue, index, array) => {
  // return true if the current element should be included in the new array
});

Example of filter()

The following code creates a new array that contains only the even numbers in the original array:

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter(n => n % 2 === 0);

console.log(evenNumbers); // [2, 4]

Reducing an array using reduce()

reduce() is used to aggregate the values of an array into a single value. Use reduce() when you need to perform some operation on every element in an array and combine the results into a single value.

Syntax of reduce()

const result = originalArray.reduce((accumulator, currentValue, index, array) => {
  // return the new value of the accumulator
}, initialValue);

Example of reduce()

The following code uses the reduce() method to add up all of the numbers in an array:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((a, b) => a + b);

console.log(sum); // 15

Examples using map, filter, reduce all at once

Example-1:

Below example gives the name and total age of persons above 25.

const users = [
  { name: "John Doe", age: 26 },
  { name: "Jane Doe", age: 23 },
  { name: "Peter Smith", age: 30 },
];

// Create a new array that contains only the users who are over the age of 25.
const adults = users.filter(user => user.age >= 25);

// Create a new array that contains the names of all the adults.
const adultNames = adults.map(user => user.name);

// Add up the ages of all the adults.
const totalAge = adults.reduce((a, b) => a + b.age);

console.log(adults); // [{ name: "John Doe", age: 25 }, { name: "Peter Smith", age: 30 }]
console.log(adultNames); // ["John Doe", "Peter Smith"]
console.log(totalAge); // 55

Example-2:

Let’s say you have an array of user objects, each containing the user’s name, age, and email address. You want to find the total number of users who are over 18 years old and have a Gmail email address, and also get the average age of those users.

const users = [
  { name: 'Alice', age: 25, email: 'alice@gmail.com' },
  { name: 'Bob', age: 30, email: 'bob@yahoo.com' },
  { name: 'Charlie', age: 20, email: 'charlie@gmail.com' },
  { name: 'Dave', age: 18, email: 'dave@gmail.com' },
  { name: 'Emily', age: 22, email: 'emily@hotmail.com' },
  { name: 'Frank', age: 28, email: 'frank@gmail.com' },
];

const gmailUsersOver18 = users.filter(user => user.age > 18 && user.email.endsWith('@gmail.com'));
const gmailUsersOver18Count = gmailUsersOver18.length;
const gmailUsersOver18TotalAge = gmailUsersOver18.reduce((totalAge, user) => totalAge + user.age, 0);
const gmailUsersOver18AvgAge = gmailUsersOver18TotalAge / gmailUsersOver18Count;

console.log(`There are ${gmailUsersOver18Count} Gmail users over 18 years old with an average age of ${gmailUsersOver18AvgAge}.`);

In this example, we use filter() to find all the users who are over 18 years old and have a Gmail email address. Then, we use length to get the total number of users who meet this criteria. We also use reduce() to calculate the total age of those users, and then divide by the count to get the average age.

Conclusion

Getting into coding has become easier with lots of tools at your disposal. Go to job sites like indeed.com or dice.com and you’d see a plethora of well paying software development related jobs. However, it is important that to land these jobs, you have the right skills. Check out the coding video courses on ReviewNPrep to master the languages.

Did you know that with ReviewNPrep CodeHub, you can practice coding online with exercises baked into the platform. Check out ReviewNPrep Code Hub today.

Further Reading:

Understand the differences between web developer and web designer in this blog.

Starting your dev career? Check out this blog to understand Python vs Java Full Stack Development.

Image by pressfoto