Recently, DUE to the work of LAN, FA, ZUO, I produced many articles based on translation. Before that, I translated the article “How to better use arrays in JavaScript”. I find that many students are not familiar with array.prototype.reduce, and I happen to have accumulated some knowledge in this area, so I would like to share it with you.
Array.prototype.reduce is one of the most difficult and powerful methods in JavaScript arrays. In this article, I will show you how to use this method with practical examples, but I will not dig into the essence of this method (which involves a lot of functional programming knowledge).
Array.prototype.reduce
A brief introduction to
The reduce() method applies a function to each element (left to right) in the accumulator and array, reducing it to a single value.
Arr. Reduce (Callback (Accumulator, currentValue[, index[, array]])[, initialValue]). Callback takes four parameters: accumulator. Callback is an accumulator. CurrentValue, the element being processed in the array; CurrentIndex (optional), the index of the current element being processed in the array; Array (Optional), the array that calls reduce(). InitialValue is an optional parameter, as the value of the first parameter when the callback function is first called. The return value of the method is the result of the cumulative processing of the function.
After a rush of introduction, it is estimated that many students are more meng. It’s not that hard to understand, and as the name suggests, get to the heart of it: aggregation. In general, if you need to convert an array to other elements, such as strings, numbers, objects, or even a new array, you can consider the reduce method if other array methods are not applicable. For those of you who are not familiar with this method, forget the syntax above and remember that the core of this method is aggregation.
The following examples use the following array, assuming the following data body is retrieved through the interface:
[{
id: 1,
type: 'A',
total: 3
}, {
id: 2,
type: 'B',
total: 5
}, {
id: 3,
type: 'E',
total: 7
},...]
Copy the code
The data body is sorted in ascending order by ID. The total and type may not be ~
Aggregate into numbers
Based on the above data body, let’s do the first small requirement together and count the total. If you do not use reduce, it is not difficult:
function sum(arr) {
let sum = 0;
for (let i = 0, len = arr.length; i < len; i++) {
const { total } = arr[i];
sum += total;
}
return sum;
}
Copy the code
This function can do all of this, but we maintain the array index precisely, and then handle the entire operation precisely, which is typical of imperative programming. As mentioned above, reduce can be used whenever it involves converting an array to another data body, which can be written like this:
arr.reduce((sum, { total }) => {
return sum + total;
}, 0)
Copy the code
And then we’re done. Sum is the sum of the previous summation, and it starts at 0. The return value of the callback function is the previous cumulative value plus the total of the current item each time, which is used as the argument to sum in the next execution. It looks rather convoluted, you can refer to the table below:
rounds | sum |
total |
The return value |
---|---|---|---|
1 | 0 (initial value) | 3 | 3 |
2 | 3 | 5 | 8 |
3 | 8 | 7 | 15 |
. | . | . | . |
Isn’t that a lot clearer? The return value of the previous one is the sum of the next one, and so on, accumulating the sum to aggregate the array into numbers.
Aggregate into strings
The next requirement is to convert each entry of the array to A fixed-form string (such as the first entry to id:1,type:A;) , each item is directly separated by a semicolon. In general, the join method is a good choice for converting arrays to strings, but it is not suitable for cases where precise control is required or where the array items are complex. In this case, the join method does not do what we want.
A for loop would certainly solve the problem, but reduce might be a better choice, as follows:
arr.reduce((str, { id, type }) => { return str + `id:${id},type:${type}; `; }, ' ')Copy the code
With the aggregation to numbers example, can you simulate the execution in your mind this time? The following is the implementation process of the first three items:
rounds | str |
id |
type |
The return value |
---|---|---|---|---|
1 | “(initial value) | 1 | ‘A’ | ‘id:1,type:A; ‘ |
2 | ‘id:1,type:A; ‘ | 2 | ‘B’ | ‘id:1,type:A; id:2,type:B; ‘ |
3 | ‘id:1,type:A; id:2,type:B; ‘ | 3 | ‘E’ | ‘id:1,type:A; id:2,type:B; id:3,type:E; ‘ |
. | . | . | . | . |
Aggregate as object
Now that we have a little foundation, we can do a little more complex aggregation. The above data body is a typical result returned by the back-end interface, but for the front end, it is more convenient to convert it into a key value object for subsequent operations. Let’s target objects where key is id and value is some other attribute.
function changeToObj(arr) {
const res = {};
arr.forEach(({ id, type, total }) => {
res[id] = {
type,
total
};
})
return res;
}
Copy the code
As shown above, this function does the job perfectly. But a little verbose, remember: You can consider using Reduce whenever your goal is to aggregate an array into unique elements. This example fits nicely:
arr.reduce((res, { id, type, total }) => {
res[id] = {
type,
total
};
return res;
}, {})
Copy the code
Res is the last object to be returned, and the code is fairly clean and powerful by iterating through the array and adding new attributes and values.
Finally, for those of you unfamiliar with this approach, you can practice converting the data body to an array of strings, each of which is the value of the original array type.
summary
That’s the end of this article, with a brief summary of the pros and cons of Reduce. In principle, it can be implemented as long as arrays are aggregated into unique elements. It also has a place in functional programming and is a good example of declarative programming. This also means that it is not easy to learn, and if you are familiar with the Reduce approach, the code you write is readable and elegant. But in the eyes of unfamiliar students, this is a real mystery. How to better use reduce and avoid writing codes that are difficult to maintain is worth every student’s consideration.
Thank you to see the adult here, easy to know, I hope this article is helpful to you ~ thank you!