js A collection of common methods
reduce
reduce() Traverse the current array , And a built-in callback function , Get... By parameters pre cur Define initial values, etc , Return any value you want to return .
pre: Get previous round return Result
cur: Get the element currently being traversed
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(previousValue, currentValue) => {
return previousValue + currentValue
},
initialValue
);
console.log(sumWithInitial);
// expected output: 10const arr = [
{
age: 12,
sex: ' male ',
name: ' Xiao Ming ',
},
{
age: 10,
sex: ' Woman ',
name: ' Xiaohong ',
},
{
age: 9,
sex: ' Woman ',
name: ' floret ',
},
]
arr.reduce((prev, cur) => {
return {
...prev,
[` Student _${cur.name}`]: cur.sex,
};
}, {})
// expected output:
{
Student _ Xiao Ming : " male "
Student _ Xiaohong : " Woman "
Student _ floret : " Woman "
} Official explanation
reduce Execute... For each element in the array in turn callback function
Accept four parameters :
accumulator Accumulator
currentValue Current value
currentIndex Current index
array Array
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator + currentValue;
});
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue
}, 10)tips: It's usually safer to provide initial values
Provided initialValue, From the index 0 Start . If not provided initialValue,reduce From the index 1 Where we started callback Method , Skip the first index .
If the array has only one element , And it didn't provide initialValue, Then this unique value will be returned and callback Will not be executed .
Look at a few others
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
,initialValue
);
console.log(sum) // logs 6
![[Day2 intensive literature reading] time in the mind: using space to think about time](/img/7a/b155ee0c136f911a7e99e9633af246.png)
![[day11-12 intensive literature reading] on languages in memory: an internal clock account of space-time interaction](/img/85/4486bd46b5f32331ce398e42e5d803.png)






