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. [Linux]Vim的安装及使用

    1.安装:$sudo apt-get install vim 2.查看Vim所在路径$whereis vim 3.启动Vim $'/usr/bin/vim.tiny'  4. 退出Vim窗口:Ctrl ...

  2. mysql datestamp坑

    每次更改行数据,该行第一个datestamp如不赋值,会自动更新为当前时间.赋值还要注意用下new Date(time).updated_at要写在created_at前面...

  3. 学习总结之Log4NET

    通过在网上查找了一些资料,用了些时间学习了log4NET,做了一个小小的总结,说一下它的特点吧 首先呢log4NET是.Net下一个非常优秀的开源日志记录组件.它可以将日志分成不同等级,也可以按照我们 ...

  4. Runtime-b

    感谢大神分享 依旧是网上很多runtime的资料,依旧是看不懂,,,这里给大家转化一下runtime,使它由隐晦难懂变得通俗易懂. (虽然截图和语言组织的有些凌乱,但是大家还是一点一点的阅读下去吧,可 ...

  5. SpringSecurity数据库中存储用户、角色、资源

    这几天项目中用到了SpringSecurity做登陆安全.所以在这写一下也许可以帮助一下其他人,自己也熟悉一下 SpringSecurity配置文件如下: <beans:beans xmlns= ...

  6. Linux相关命令

    使用的是ubuntu 安装JDK   输入java 命令会有提示安装的软件列表 sudo apt-get install openjdk-6-jdk sudo rm file名 删除文件 sudo r ...

  7. struts2中的标签“# ”,“%{ }”,“%{# }”

    理解值栈(ValueStack)与上下文(StackContext):            Struts2中有值堆栈和堆栈上下文的概念,你用 <s:debug />可以看出. 值栈中的对 ...

  8. jQuery 表格插件25

    jQuery 表格插件可以让你创建各种各样的表格布局,表格布局是报纸和杂志中最常见的布局,现在的网站中也很常见,在这篇文章中,我向大家推荐25个jQuery 的表格插件,你可以任意控制表格的行和列,用 ...

  9. BZOJ 3680 吊打XXX

    Description gty又虐了一场比赛,被虐的蒟蒻们决定吊打gty.gty见大势不好机智的分出了n个分身,但还是被人多势众的蒟蒻抓住了.蒟蒻们将n个gty吊在n根绳子上,每根绳子穿过天台的一个洞 ...

  10. angularjs 资源集合

    AngularJS是Google开源的一款JavaScript MVC框架,弥补了HTML在构建应用方面的不足. 源码托管在Github上,其通过使用指令(directives)结构来扩展HTML词汇 ...