By the end of this lesson, you will understand how to transform and filter arrays using the map and filter methods in JavaScript.
In JavaScript, map and filter are two powerful methods that help you work with arrays. The map method creates a new array by applying a function to every element of an original array. On the other hand, the filter method creates a new array that includes only the elements that meet certain conditions.
For example, imagine you have a list of ages, and you only want to find the ages that are greater than 18. You can use filter to extract this information. If you want to double each age in the list, then you would use map. As a result, both methods help you manage arrays effectively.
File: array-transform.php
const ages = [15, 20, 25, 30, 10];
// Filter ages greater than 18
const adults = ages.filter(age => age > 18);
console.log(adults);
// Double each age using map
const doubledAges = ages.map(age => age * 2);
console.log(doubledAges);
Expected Output:
[20, 25, 30]
[30, 40, 50, 60, 20]
In this code, we transform and filter arrays with the following lines:
filter(age => age > 18) checks each age and includes it in the new array if it is greater than 18.map(age => age * 2) multiplies each age in the original array by 2 and includes it in the new array.Now it’s your turn! Create an array of numbers representing scores from a game. Use filter to find scores greater than 50. Then, you will use map to add 10 points to each score. This exercise will help strengthen your understanding.
File: game-scores.php
const scores = [45, 55, 70, 30, 90];
// Filter scores greater than 50
const highScores = scores.filter(score => score > 50);
console.log(highScores);
// Add 10 points to each score
const adjustedScores = scores.map(score => score + 10);
console.log(adjustedScores);
Here are two common mistakes and how to fix them:
return or the concise body syntax without braces. For example, use age => age > 18 instead of age => { return age > 18; }.map and filter: Remember that map creates a new array of the same length, while filter creates a new array that may be shorter. Therefore, clarify their uses to avoid errors.map to transform each element of an array into a new array.filter to create a new array with only elements that meet certain conditions.