1. Map: Map the new world
Map
The constructor creates a new Map object that allows you to store data in the form of key-value pairs, providing a more flexible data structure. Compared to traditional objects, Map allows any value (including objects) as keys and has better performance.
Application scenario: Data conversion
When you need to convert each element of the array into a new value by some rule,Map
The method seems particularly handy.
const numbers = [1, 2, 3, 4]; // Use the Map method to square each numberconst squaredNumbers = (num => num * num); (squaredNumbers); // Output:[1, 4, 9, 16]
In this example,map
Method traverse arraynumbers
, apply a function for each element (in this case a square operation) and collect the results into a new arraysquaredNumbers
middle.
2. Reduce: Simplify the complexity
reduce
Methods are another powerful tool that can accumulate array elements to a single value. This is very useful for statistical calculations (such as summing, product), array flattening and other scenarios.
Application scenario: Array summing and complex data aggregation
Let's look at a simple example of how to use itreduce
To calculate the sum of an array of numbers.
const values = [1, 2, 3, 4, 5]; // Use reduce method to calculate the sum of the arrayconst sum = ((accumulator, currentValue) => accumulator + currentValue, 0); (sum); // Output:15
here,reduce
Receives a callback function that has two parameters: accumulator and current value (currentValue). The initial value (0 in this example) is the optional second parameter to initialize the accumulator's value.
Going further,reduce
It can also handle more complex data aggregation tasks. For example, extract the values of a specific attribute from a set of objects and merge them into a new object.
const items = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]; // Use reduce to extract and integrate the name attribute into a new objectconst namesById = ((accumulator, currentItem) => { accumulator[] = ; return accumulator; }, {}); (namesById); // Output:{1: "Alice", 2: "Bob", 3: "Charlie"}
In the above code,reduce
Not only does the data aggregation be completed, but the data structure is also transformed, demonstrating its flexibility and powerful functions.
This is the end of this article about the application of Map and reduce in JavaScript. For more related JavaScript Map and reduce content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!