[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 simple and when harnessed correctly can achieve very powerful results. By leveraging reduce, we can answer a variety of questions on a single, simple data set. In this lesson, we'll look at how you might useArray.prototype.reduce to:
- Sum an array of numbers
- Reduce an array of objects to a sum of a given property
- Group an array of objects by key or a set of given criteria
- Count the number of objects in an array by key or a given set of criteria
- let numbers = [1,2,3,4,5];
- console.clear();
- numbers.reduce(function(preVal, curVal, index, array){
- console.log({preVal, curVal, index, array});
- return curVal;
- });
- /*
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 2,
- index: 1,
- preVal: 1
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 3,
- index: 2,
- preVal: 2
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 4,
- index: 3,
- preVal: 3
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 5,
- index: 4,
- preVal: 4
- }
- */
reduce() start from the second value in the array.
If there is no return value which will be passed to the next object as a previous value, then the next previous value will be undefined:
- var numbers = [1,2,3,4,5];
- console.clear();
- numbers.reduce(function(preVal, curVal, index, array){
- console.log({preVal, curVal, index, array});
- });
- /*
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 2,
- index: 1,
- preVal: 1
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 3,
- index: 2,
- preVal: undefined
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 4,
- index: 3,
- preVal: undefined
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 5,
- index: 4,
- preVal: undefined
- }
- */
You can give another parameter to let it start from the first element of the array:
- numbers.reduce(function(preVal, curVal, index, array){
- console.log({preVal, curVal, index, array});
- return curVal;
- }, "start");
- /**
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 1,
- index: 0,
- preVal: "start"
- }
- [object Object] {
- array: [1, 2, 3, 4, 5],
- curVal: 2,
- index: 1,
- preVal: 1
- }
- ...
- ...
- */
Sum up an number of array:
- let numbers = [1,2,3,4,5];
- console.clear();
- var sum = numbers.reduce( (preVal, curVal) => preVal + curVal);
- console.log("sum: " + sum);
- /*
- Sum: 15
- */
Example 2:
- let people = [
- {
- name: 'Joe mins',
- yearsExperience: 1,
- dapartment: 'IT'
- },
- {
- name: "Sally koral",
- yearsExperience: 15,
- dapartment: 'Engineering'
- },
- {
- name: "Bill Fork",
- yearsExperience: 5,
- dapartment: 'Engineering'
- },
- {
- name: 'Jane James',
- yearsExperience: 11,
- dapartment: 'Manager'
- },
- {
- name: 'Bob Super',
- yearsExperience: 9,
- dapartment: 'IT'
- },
- ];
- console.clear();
- var yearsExperience = people.reduce( (sum, curVal) => sum + curVal.yearsExperience, 0);
- console.log(yearsExperience); //41
Group by object:
- let people = [
- {
- name: 'Joe mins',
- yearsExperience: 1,
- dapartment: 'IT'
- },
- {
- name: "Sally koral",
- yearsExperience: 15,
- dapartment: 'Engineering'
- },
- {
- name: "Bill Fork",
- yearsExperience: 5,
- dapartment: 'Engineering'
- },
- {
- name: 'Jane James',
- yearsExperience: 11,
- dapartment: 'Manager'
- },
- {
- name: 'Bob Super',
- yearsExperience: 9,
- dapartment: 'IT'
- },
- ];
- console.clear();
- var departmentExperienceYears = people.reduce( (groupByObject, employee) => {
- let dapartment = employee.dapartment;
- if(!groupByObject[dapartment]){
- groupByObject[dapartment] = 0;
- groupByObject[dapartment] += employee.yearsExperience;
- }
- return groupByObject;
- }, {});
- console.log(departmentExperienceYears);
- /*
- [object Object] {
- Engineering: 15,
- IT: 1,
- Manager: 11
- }
- */
[JavaScript] Array.prototype.reduce in JavaScript by example的更多相关文章
- Array.prototype.reduce 的理解与实现
Array.prototype.reduce 是 JavaScript 中比较实用的一个函数,但是很多人都没有使用过它,因为 reduce 能做的事情其实 forEach 或者 map 函数也能做,而 ...
- Javascript Array.prototype.some()
当我们使用数组时,查找数组中包含某个特殊的项是非常常见的动作.下面例子是一个简单的实现: 01 planets = [ 02 "mercury", 03 " ...
- Array.prototype.reduce()
reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值. arr.reduce([callback, initialValue]) c ...
- js Array.prototype.reduce()
例子: , , , ]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 ...
- javascript:Array.prototype.slice.call(arguments)
我们知道,Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js ...
- javascript数组去重 String字符串去掉两端空格 javascript Array二分法排序 比较 javascript 求和
通过原形添加方法: ==================数组去重(对象去重法)======================= Array.prototype.unique=function(){ va ...
- 数组的方法之(Array.prototype.reduce() 方法)
reduce函数 reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值. 对数组中的所有元素调用指定的回调函数.该回调函数的返回值为累积结果,并且此返回值在下一次 ...
- JavaScript Array 常用函数整理
按字母顺序整理 索引 Array.prototype.concat() Array.prototype.filter() Array.prototype.indexOf() Array.prototy ...
- javaScript 的 map() reduce() foreach() filter()
map(映射), reduce(规约), forEach(遍历), filter(过滤),它们都是高阶函数,都是以传入不同的函数来以不同的方式操作数组元.ie都不支持 一.map方法 *概述 map( ...
随机推荐
- webserver<1>
1. 实现基础的信号处理 sigaction使用前一定内存清零 2. 实现基础的进程模型 wait 等待子进程结束 #include <stdio.h> #include <unis ...
- [HDOJ - 5208] Where is Bob 【DFS+按位贪心】
题目链接:HDOJ - 5208 题目分析 使用按位贪心的思想,即从高位向低位枚举,尽量使这一位的答案为 1 . 我们使用 DFS ,每次就是对于 [l1, r1] [l2, r2] x 进行处理 ...
- Matlab绘图系列之高级绘图
Matlab绘图系列之高级绘图 原帖地址: http://blog.163.com/enjoy_world/blog/static/115033832007865616218/ Matlab绘图 20 ...
- iOS内存管理系列之一:对象所有权与引用计数
当一个所有者(owner,其本身可以是任何一个Objective-C对象)做了以下某个动作时,它拥有对一个对象的所有权(ownership): 1. 创建一个对象.包括使用任何名称中包含“alloc” ...
- XP系统VPN设置
为了解除公司上网策略限制,或者为了上Google,Facebook,都可以通过设置VPN实现. 要使用VPN需要到VPN服务商注册,链接VPN服务商. ======================== ...
- Android假退出不是流氓行为
转自Android假退出不是流氓行为 关于Android程序的退出,目前我们没有再用System.exit(0)或killProcess的机制而是直接用Activity.finish假退出了.因此在内 ...
- 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法一网打尽
字符串模式匹配算法——BM.Horspool.Sunday.KMP.KR.AC算法一网打尽 本文内容框架: §1 Boyer-Moore算法 §2 Horspool算法 §3 Sunday算法 §4 ...
- 子窗体显示在任务栏,且子窗体中又有弹窗(CreateParams修改三个风格参数)
子窗体显示在任务栏时, procedure Tfrm_SendSmartMsg.CreateParams(var Params: TCreateParams);begin inherited; P ...
- BZOJ1699: [Usaco2007 Jan]Balanced Lineup排队
1699: [Usaco2007 Jan]Balanced Lineup排队 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 933 Solved: 56 ...
- 2015第44周五Java集群技术(转)
从http://blog.csdn.net/cdh1213/article/details/21443239上看到这篇文章,感觉很不错,找好久没找到中文出处,最早看是从http://www.these ...