Unlike other methods of traversing arrays, reduce can return any type and is more flexible.
Know the reduce
Array.reduce(callback,starValue) takes two arguments and returns a final sum (of the same type as starValue)
-
Callback: A callback method that executes on each element of the array.
-
StarValue: initial value (can be any type).
Callback (accumulator, current, currentInedex, arr) receiving four parameters: the current accumulation results, to accumulate the value of the current, the current index, the array itself
Use reduce to implement array summation
var total = [1, 2, 3].reduce(function (accumulator, current) {
return accumulator + current;
}, 0);
console.log(total) // 6
Copy the code
Reduce is used to iterate through the objects in the number group, get the values that meet the criteria in the object and return an array
const arr = [ { name: 'lgf', age: 22 }, { name: 'chm', age: 22 }, { name: 'lalal', age: 21 } ] var newArr = arr.reduce(function (accumulator, current) { if (current.age === 22) { accumulator.push(current.name); } return accumulator; } []); console.log(newArr) // ["lgf", "chm"]Copy the code
Generate HTML tags from arrays (return string type)
var nameList = arr.reduce(function (accumulator, current) { if (current.age === 22) { accumulator += '<li>' + current.name + '</li>'; } return accumulator; } "); console.log(nameList) // <li>lgf</li><li>chm</li>Copy the code
Add an object
var newArr = arr.reduce(function (accumulator, current) {
if (current.age === 22) {
const type = current.name
accumulator[type]=current.name;
}
return accumulator;
}, {});
console.log(newArr) // {lgf: "lgf", chm: "chm"}
Copy the code
Finally, let’s implement a Reduce method
Array.prototype.myReduce = function(fn, initialValue) {array.prototype. myReduce = function(fn, initialValue) {array.prototype. myReduce = function(fn, initialValue) {array.prototype. myReduce = function(fn, initialValue) {array.prototype. myReduce = function(fn, initialValue) { If the initial value is the initial value of the acc for the initialValue, or for the first value of an array of the let acc = the initialValue | | this [0] / / definition calculation index: Const startIndex = initialValue? Const startIndex = initialValue? For (let I = startIndex; let I = startIndex; let I = startIndex; let I = startIndex; let I = startIndex; i < this.length; I ++) {acc = fn(acc, this[I], I, this)}Copy the code
Check whether the parameter is valid:
Array.protopy.myReduce = function(fn,value){ if(typeof fn ! . = = 'function') {the console log (' the first argument must be a function) return} const acc = value | | this [0]. const startIndex = value ? 0 : 1 for(let i = startIndex; this.length,i++){ acc = fn(acc, this[i], i, this) } return acc }Copy the code