Writing in the front
Still worried that your JS code isn't elegant enough? Learn JavaScript higher-order functions to do your trick and make your code unreadable.Copy the code
JavaScript native higher-order functions
A higher-order function is one that takes a function as an argument or return value. Let’s learn about the Map Reduce Filter
Array.map
Grammar:
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
Copy the code
Parameter Description:
The current element being processed in the currentValue array. Index (Optional) Index of the current element being processed in the array. Array (Optional) Array called by the map method. ThisArg (optional) the value used as this when the callback function is executed.Copy the code
Simple explanation:
Process each element of the array as passed in and return a new array of the same length.Copy the code
Case Sharing:
F (x)=x^2
var arr = [1.2.3.4.5.6.7.8.9];
arr.map( item= > item * item )
// Result is: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Copy the code
Array.reduce
Grammar:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code
Parameter Description:
The return value of the accumulator callback; It is the cumulative value, or initialValue, returned when the callback was last called. The element being processed in the currentValue array. Index (Optional) Index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1. Array (optional) initialValue(optional) of the array that calls reduce() as the value of the first argument when the callback function is first called. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.Copy the code
Simple explanation:
The elements in the array execute functions one by one and the return value is remembered and passed to the next callCopy the code
Case Sharing:
// convert [1, 3, 5, 7, 9] to the integer 13579
var arr = [1.3.5.7.9];
arr.reduce((result, item) = > ( result = result*10 + item ))
// The result is 13579
// The number of occurrences per letter in a string
var str = "aabbcddeffffa"
str.split("").reduce((result, item) = > {result[item] = result[item] ? result[item] + 1 : 1; return result }, {})
// {a: 3, b: 2, c: 1, d: 2, e: 1, f: 4}
str.split("").reduce((result, item) = > ({[item]: result[item]? result[item]++: 1. result }),{})// {a: 3, b: 2, c: 1, d: 2, e: 1, f: 4}
{1: "apple", 2: "banana", 3: "orange"}
var arr = [
{ id: 1.name: "apple" },
{ id: 2.name: "banana"},
{ id: 3.name: "orange"},
]
arr.reduce((obj, item) = > ({
...obj,
[item.id]: item.name
}), {})
// {1: "apple", 2: "banana", 3: "orange"}
Copy the code
Array.filter
Grammar:
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
Copy the code
Parameter Description:
Element The element in the array that is currently being processed. Index (Optional) Index of the element being processed in the array. Array (optional) calls the array of filter itself. ThisArg (optional) The value used for this when callback is executed.Copy the code
Simple explanation:
A filter filters out some elements of an array and returns the restCopy the code
Case Sharing:
// Filter out the cardinality
var arr = [1.7.4.2.6.9.10.11];
arr.filter(function (x) {
return x % 2! = =0;
});
// The result is: [1, 7, 9, 11]
Copy the code
Comprehensive use of
The following example realizes a process of summing the data filtering process; Let’s get a sense of it
// This is a complex example of a process that aims to implement the summation of data filtering processes
// Define the initial data
var personnel = [
{
id: 5.name: "Luke Skywalker".pilotingScore: 98.shootingScore: 56.isForceUser: true}, {id: 82.name: "Sabine Wren".pilotingScore: 73.shootingScore: 99.isForceUser: false}, {id: 22.name: "Zeb Orellios".pilotingScore: 20.shootingScore: 59.isForceUser: false}, {id: 15.name: "Ezra Bridger".pilotingScore: 43.shootingScore: 67.isForceUser: true}, {id: 11.name: "Caleb Dume".pilotingScore: 71.shootingScore: 85.isForceUser: true,},];// Filter out isForceUser = true
jediPersonnel = personnel.filter(function (person) {
return person.isForceUser;
});
// Result: [{...}, {...}, {...}] (Luke, Ezra and Caleb)
// Calculate the sum of the driving and shooting scores for each element in the array
var jediScores = jediPersonnel.map(function (jedi) {
return jedi.pilotingScore + jedi.shootingScore;
});
// Result: [154, 110, 156]
// Finally calculate the sum of all scores
var totalJediScore = jediScores.reduce(function (acc, score) {
return acc + score;
}, 0);
// Result: 420
// Merge code
totalJediScore = personnel
.filter(person= > person.isForceUser)
.map(jedi= > jedi.pilotingScore + jedi.shootingScore)
.reduce((acc, score) = > acc + score, 0);
Copy the code
conclusion
- There are similar higher-order functions in other languages that essentially do the same thing if you read this
map/reduce/filter
It’s easy - General looping can do the same thing, but there’s always something to write code for. Read and learn from other people’s code, and you’ll be able to write simpler and more elegant code.
- It may not be easy for beginners to understand the logic of this, but if you build on understanding
map/reduce/filter
On the contrary, we can understand the logic of it more clearly.
The resources
JavaScript standard built-in objects
Illustrate Map, Reduce, and Filter array methods
An Illustrated (and Musical) Guide to Map, Reduce, and Filter Array Methods