[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( ...
随机推荐
- JQuery 字符串截取
//字符串截取,全小写 strObj.substring(startIndex,endIndex); //需要注意大小写 strObj.lastIndexOf(String splitObj); // ...
- <string> <string.h>
在C++开发过程中经常会遇到两个比较容易混淆的头文件引用#include<string.h> 和 #include<string>,两者的主要区别如下: #include< ...
- linux内核源码结构
一.概述 Linux内核庞大,但是这些文件的结构还是有章可循的,分别位于不同的目录下,各个目录功能相对独立. 二.源码结构表 目录名 描述 arch 体系结构相关的代码,对于每个架构的CPU,arch ...
- NET Core+Code First+Docker
NET Core+Code First+Docker背景介绍 本文将会示范如何在Windows系统下基于ASP.NET Core构建跨平台服务,并通过Docker容器运行发布. 首先说一下为什么选择这 ...
- 通过jquery获取后台传过来的值进行全选
注:funs是从action中传过来的list<Function> 其中属性中有其子对象list<role> 下面通过s标签遍历 ,也可以通过c标签遍历 jsp页面中: < ...
- Shoot the Bullet
zoj3229:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3442 题意:一个摄影师,在n天内给m个女神拍照.每个女神至少要 ...
- Redis3在CENTOS6上的安装配置
重温一下,这次找了个简单的安装. 测试过程很顺利哟. 参考URL: http://www.linuxidc.com/Linux/2015-07/119567.htm 一.介绍 redis在做数据库缓存 ...
- [cocos2d]关于CCSprite的若干问题与误区
文章 [cocos2d] 利用texture atlases生成动画 中介绍了如何生成动画并绑定在CCSprite实例上. 使用该代码遇到了几个问题,值得mark下 问题1.多实例 问题描述: 新建一 ...
- 【HDOJ】3006 The Number of set
数据量这么小,果断状态压缩+dp. /* 3006 */ #include <iostream> #include <string> #include <map> ...
- 【HDOJ】3205 Factorization
题意很简单.就是求x^k-1的因式分解.显然x-1必然是其中之一(x=1, x^k-1=0).假设k=mp. 则x^k = (x^p)^m, 同理x^p-1必然是其中之一,即x^p的所有因式一定是x^ ...