例子:

const array1 = [, , , ];
const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10 // 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, ));
// expected output: 15

reducer 函数接收4个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)

您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。

例子

数组里所有值的和

函数表示伐:

var sum = [, , , ].reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, ); console.log(sum)

你也可以写成箭头函数的形式:

var total = [ , , ,  ].reduce(
( acc, cur ) => acc + cur, );
console.log(total);

累加对象数组里的值

要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数。

var initialValue = ;
var sum = [{x: }, {x:}, {x:}].reduce(function (accumulator, currentValue) {
return accumulator + currentValue.x;
},initialValue) console.log(sum) // logs 6

你也可以写成箭头函数的形式

var initialValue = ;
var sum = [{x: }, {x:}, {x:}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
,initialValue
); console.log(sum)

将二维数组转化为一维

var flattened = [[, ], [, ], [, ]].reduce(
function(a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]

你也可以写成箭头函数的形式

var flattened = [[, ], [, ], [, ]].reduce(
( acc, cur ) => acc.concat(cur),
[]
);

计算数组中每个元素出现的次数

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = ;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

按属性对object分类

var people = [
{ name: 'Alice', age: },
{ name: 'Max', age: },
{ name: 'Jane', age: }
]; function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
} var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }

使用扩展运算符和initialValue绑定包含在对象数组中的数组

// friends - 对象数组
// where object field "books" - list of favorite books
var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age:
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age:
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age:
}]; // allbooks - list which will contain all friends' books +
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
return [...prev, ...curr.books];
}, ['Alphabet']); // allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]

数组去重

let arr = [,,,,,,,,,,,,];
let result = arr.sort().reduce((init, current)=>{
if(init.length=== || init[init.length-]!==current){
init.push(current);
}
return init;
}, []);
console.log(result); //[1,2,3,4,5]

按顺序运行Promise

/**
* Runs promises from array of functions that can return promises
* in chained manner
*
* @param {array} arr - promise arr
* @return {Object} promise object
*/
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input)
);
} // promise function 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a * );
});
} // promise function 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a * );
});
} // function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a * ;
} // promise function 4
function p4(a) {
return new Promise((resolve, reject) => {
resolve(a * );
});
} const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, )
.then(console.log); //

功能型函数管道

// Building-blocks to use for composition
const double = x => x + x;
const triple = x => * x;
const quadruple = x => * x; // Function composition enabling pipe functionality
const pipe = (...functions) => input => functions.reduce(
(acc, fn) => fn(acc),
input
); // Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple); // Usage
multiply6(); //
multiply9(); //
multiply16(); //
multiply24(); //

Polyfill

// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, 'reduce', {
value: function(callback /*, initialValue*/) {
if (this === null) {
throw new TypeError( 'Array.prototype.reduce ' +
'called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback +
' is not a function');
} // 1. Let O be ? ToObject(this value).
var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> ; // Steps 3, 4, 5, 6, 7
var k = ;
var value; if (arguments.length >= ) {
value = arguments[];
} else {
while (k < len && !(k in o)) {
k++;
} // 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
value = o[k++];
} // 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// « accumulator, kValue, k, O »).
if (k in o) {
value = callback(value, o[k], k, o);
} // d. Increase k by 1.
k++;
} // 9. Return accumulator.
return value;
}
});
}

js Array​.prototype​.reduce()的更多相关文章

  1. Array.prototype.reduce()

    reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值. arr.reduce([callback, initialValue]) c ...

  2. Array.prototype.reduce 的理解与实现

    Array.prototype.reduce 是 JavaScript 中比较实用的一个函数,但是很多人都没有使用过它,因为 reduce 能做的事情其实 forEach 或者 map 函数也能做,而 ...

  3. [JavaScript] Array.prototype.reduce in JavaScript by example

    Let's take a closer look at using Javascript's built in Array reduce function. Reduce is deceptively ...

  4. js Array.prototype.slice.call(arguments,0) 理解

    Array.prototype.slice.call(arguments,0) 经常会看到这段代码用来处理函数的参数 网上很多复制粘帖说:Array.prototype.slice.call(argu ...

  5. 【笔记】js Array.prototype.slice.call(arguments) 将函数的参数转换为数组方法的见解

    我们知道函数里面的参数实际上是一个以数组形式储存的对象 但它并非一个数组 如果我们要将它转换为数组可以调用Array.prototype.slice() 这个方法 分析一下这个方法: Array.pr ...

  6. js Array.prototype.join.call(arguments,",") 理解

    prototype 属性使您有能力向对象添加属性和方法. join() 方法:把数组的所有元素放入一个字符串.元素通过指定的分隔符进行分隔. call() 方法可以用来代替另一个对象调用一个方法. A ...

  7. 数组的方法之(Array.prototype.reduce() 方法)

    reduce函数 reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值. 对数组中的所有元素调用指定的回调函数.该回调函数的返回值为累积结果,并且此返回值在下一次 ...

  8. JS - Array.prototype.sort(compare)

    function compare(a, b) { return -1; // a 在 b 前面 return 1; // a 在 b 后面 return 0; // 并列排序,保持在源数组中的先后顺序 ...

  9. JS Array常用方法indexOf/filter/forEach/map/reduce详解

    Array共有九个方法   Array.prototype.indexOf Array.prototype.lastIndexOf Array.prototype.every Array.protot ...

随机推荐

  1. Oracle课程档案,第十天

    用户管理 Authentication: 身份验证 AAA:Authentication: 身份验证 Authorization: 权限管理 Audition: 审计 grant:授权 unset:撤 ...

  2. js的运用1

    1.parselnt() 2.parsefloat() 遇到第一个字节是非数字就结束了. 3.      var   a="hello world" a这个变量是字符串了,对于里面 ...

  3. ELK之elasticsearch导致CPU居高不下系统慢解决办法

    参考:http://zoufeng.net/2018/07/16/cpu-of-elasticsearch-high-search-slow/ elasticsearch主机CPU居高不下100%左右 ...

  4. SQL Fundamentals: 子查询 || 分析函数(PARTITION BY,ORDER BY, WINDOWING)

    SQL Fundamentals || Oracle SQL语言 子查询(基础) 1.认识子查询 2.WHERE子句中使用子查询 3.在HAVING子句中使用子查询 4.在FROM子句中使用子查询 5 ...

  5. XSS笔记

    XSS测试代码: <img src="javascript:alert(/xss/)"> <script src=http://evil.com/xss.js&g ...

  6. Pycharm调试:进入调用函数后返回

    在菜单栏的view中勾选toolbar,然后点击工具栏中左箭头返回到调用函数处.

  7. CSS中的display属性(none,block,inline,inline-block,inherit)

    css中的display属性(none,block,inline,inline-block,inherit) display属性是我们在前端开发中常常使用的一个属性,其中,最常见的有: none bl ...

  8. 阻塞队列(BlockingQueue)

    阻塞队列是 java.util.concurrent 包提供的一个类,该类提供了多线程中通过队列实现安全高效的数据处理的功能. 所谓阻塞队列,是在普通队列基础上实现了阻塞线程的功能: 队列为空时,获取 ...

  9. 002-红黑树【B-树】、二叉查找树

    一.引述-二叉查找树 红黑树(Red Black Tree) 一种特殊的二叉查找树.故先查看二叉查找树 二叉查找树特性:左字数上所有的节点的值都小于或等于他的根节点上的值 右子树上所有节点的值均大于或 ...

  10. [js]js设计模式-原型模式

    构造函数模型- 对象的属性和方法每人一份 function createJs(name, age) { this.name = name; this.age = age; this.writeJs = ...