- An Illustrated (and Musical) Guide to Map, Reduce, and Filter Array Methods
- Una Kravets
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Xiong Xianren
- Proofreader: Endone, Reaper622
Map, Reduce, and Filter are three very useful JavaScript array methods that give developers a lot of power. Let’s get right down to business and see how to use (and remember) these super handy tips!
Array.map()
Array.map() updates each value in the given Array based on the passed conversion function and returns a new Array of the same length. It takes a callback function as an argument to perform the conversion process.
let newArray = oldArray.map((value, index, array) = >{... });Copy the code
Morph Array piece-by-piece one way to help remember a map: Morph Array piece-by-piece
Instead of a for-each loop, you can use map to iterate over and apply conversion functions to each value. This method is useful when you want to update an array while preserving the original values. It does not potentially remove any values (the Filter method does), nor does it compute a new output (as reduce does). Map allows you to change arrays one by one. Let’s look at an example:
[1.4.6.14.32.78].map(val= > val * 10)
// the result is: [10, 40, 60, 140, 320, 780]
Copy the code
In the example above, we use an initial array ([1, 4, 6, 14, 32, 78]) that maps each value to ten times itself (val * 10). The result is a new array, with each value of the original array converted by this equation: [10, 40, 60, 140, 320, 780].
Array.filter()
The quick and useful method array.filter () comes in handy when we want to filter an Array of values to another Array, with each value in the new Array passing a specific check.
Similar to a search filter, a filter filters out values based on passed parameters.
For example, if you have an array of numbers and want to filter out values greater than 10, you can write:
[1.4.6.14.32.78].filter(val= > val > 10)
// the result is: [14, 32, 78]
Copy the code
Using the map method on this array, as in the example above, returns an array with val > 10 of the same length as the original array, where each value is converted or checked. If the original value is greater than 10, it is converted to true. Something like this:
[1.4.6.14.32.78].map(val= > val > 10)
// the result is: [false, false, false, true, true, true]
Copy the code
The filter method, however, returns only the true value. So if all values are checked as specified, the length of the result will be less than or equal to the original array.
Think of a filter as a funnel. Some of the mixture passes through into the result, while others are left behind and discarded.
Suppose a pet training school has a small class of four dogs, and all the dogs in the school go through various challenges and then take a graded final exam. We represent these dogs with an array of objects:
const students = [
{
name: "Boops".finalGrade: 80
},
{
name: "Kitten".finalGrade: 45
},
{
name: "Taco".finalGrade: 100
},
{
name: "Lucy".finalGrade: 60}]Copy the code
Dogs get a fancy certificate if they score more than 70 on a final exam; If not, they have to rebuild. To know how many certificates are printed, write a method that returns the dog that passed the test. Instead of writing a loop through every object in a group, we can simplify the code with filter!
const passingDogs = students.filter((student) = > {
return student.finalGrade >= 70
})
/* passingDogs = [ { name: "Boops", finalGrade: 80 }, { name: "Taco", finalGrade: 100 } ] */
Copy the code
As you can see, Boops and Taco are good dogs (and all dogs are good dogs) and have a certificate of achievement for passing the course! Using the implicit return feature of the arrow function, this can be done in one line of code. Since there is only one argument, we can delete the parentheses of the arrow function:
const passingDogs = students.filter(student= > student.finalGrade >= 70)
/* passingDogs = [ { name: "Boops", finalGrade: 80 }, { name: "Taco", finalGrade: 100 } ] */
Copy the code
Array.reduce()
The reduce() method takes an array as input and returns a value. This is interesting. Reduce takes a callback function that takes an accumulator (the sum of each segment of the array, which grows like a snowball), the current value, and the index. Reduce also accepts an initial value as a second argument:
let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array) = >{... }), initalValue;Copy the code
Write a frying function and a list of ingredients:
// our list of ingredients in an array
const ingredients = ['wine'.'tomato'.'onion'.'mushroom']
// a cooking function
const cook = (ingredient) = > {
return `cooked ${ingredient}`
}
Copy the code
If we want to make a sauce out of these ingredients (just kidding), reduce()!
const wineReduction = ingredients.reduce((sauce, item) = > {
return sauce += cook(item) + ', '
}, ' ')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "
Copy the code
The initial value (” in this case) is important and determines that the first ingredient will be ready for cooking. The output here is not very reliable, so be careful when cooking yourself. Here’s an example of what I’m talking about:
const wineReduction = ingredients.reduce((sauce, item) = > {
return sauce += cook(item) + ', '
})
// wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "
Copy the code
Finally, to ensure that there is no extra whitespace at the end of the new string, we can pass indexes and arrays to perform the conversion:
const wineReduction = ingredients.reduce((sauce, item, index, array) = > {
sauce += cook(item)
if (index < array.length - 1) {
sauce += ', '
}
return sauce
}, ' ')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
Copy the code
You can use the ternary operator, template strings, and implicit returns to write more succinctly (one line!). :
const wineReduction = ingredients.reduce((sauce, item, index, array) = > {
return (index < array.length - 1)? sauce +=`${cook(item)}, ` : sauce += `${cook(item)}`
}, ' ')
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"
Copy the code
An easy way to remember this method is to think back to how you make a sauce: reduce multiple ingredients to a single ingredient.
Sing with me!
I’d like to end this post with a song, a little ditty for array methods to help you remember:
Video
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.