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的更多相关文章

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

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

  2. Javascript Array.prototype.some()

    当我们使用数组时,查找数组中包含某个特殊的项是非常常见的动作.下面例子是一个简单的实现: 01 planets = [ 02     "mercury", 03     " ...

  3. Array.prototype.reduce()

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

  4. js Array​.prototype​.reduce()

    例子: , , , ]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 ...

  5. javascript:Array.prototype.slice.call(arguments)

    我们知道,Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js ...

  6. javascript数组去重 String字符串去掉两端空格 javascript Array二分法排序 比较 javascript 求和

    通过原形添加方法: ==================数组去重(对象去重法)======================= Array.prototype.unique=function(){ va ...

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

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

  8. JavaScript Array 常用函数整理

    按字母顺序整理 索引 Array.prototype.concat() Array.prototype.filter() Array.prototype.indexOf() Array.prototy ...

  9. javaScript 的 map() reduce() foreach() filter()

    map(映射), reduce(规约), forEach(遍历), filter(过滤),它们都是高阶函数,都是以传入不同的函数来以不同的方式操作数组元.ie都不支持 一.map方法 *概述 map( ...

随机推荐

  1. 制作font-icon有感

    连日来有些空闲,趁着这闲余时间,我尝试亲自制作一些Font-Icon,让以后可以运用到工作中.但是基于本人水平有限,PS操作只能以非常基础来形容,而AI呢,根本就只会放大操作.在这过程真的非常感谢设计 ...

  2. CSS and JavaScript Bundling and Minification in ASP.NET 4.5

    ASP.NET 4.5 includes a new feature to minify and bundle CSS and JavaScript within your web applicati ...

  3. Cinder-1 TinderBox

    Cinder:http://libcinder.org/,当前版本是0.8.5,代码托管位置:https://github.com/cinder/Cinder.git 下载Cinder之后,其目录结构 ...

  4. 练习2 H题 - 求数列的和

      Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u   Description 数列的 ...

  5. union 与struct的空间计算

    一.x86 总体上遵循两个原则: 整体空间----占用空间最大的成员(的类型)所占字节数的整数倍 对齐原则----内存按结构成员的先后顺序排列,当排到该成员变量时,其前面已摆放的空间大小必须是该成员类 ...

  6. 切换view的动画

    代码: #import "MainViewController.h" @interface MainViewController () @end @implementation M ...

  7. golang开发android环境搭建_window

    golang开发android环境搭建介绍 一 安装依赖软件: git:版本管理 go:  go开发环境(版本>=1.5),可直接下载window版的go安装包. android studio: ...

  8. Zoj 3865 Superbot

    按规则移动机器人 , 问是否能拾得宝藏 . 加了一个控制板 , 还增加了一个控制板移动周期 p 将移动周期变换一下 , 移动一次  就相当于光标向左不耗费时间的移动了一格 搜索思路 : 搜索当前格子到 ...

  9. 线性表之顺序存储结构(C语言动态数组实现)

    线性表的定义:N个数据元素的有限序列 线性表从存储结构上分为:顺序存储结构(数组)和 链式存储结构(链表) 顺序存储结构:是用一段连续的内存空间存储表中的数据 L=(a1,a2,a3....an) 链 ...

  10. spm使用之七不用seajs改用headjs起步

    这几天在看phpwind官方网站, 他们的前端用了一个叫做head.js的js加载器, 官方网站在 http://headjs.com/ 号称是你只需要在你的html文件中的<head>& ...