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
  1. let numbers = [1,2,3,4,5];
  2.  
  3. console.clear();
  4.  
  5. numbers.reduce(function(preVal, curVal, index, array){
  6. console.log({preVal, curVal, index, array});
  7. return curVal;
  8. });
  9.  
  10. /*
  11. [object Object] {
  12. array: [1, 2, 3, 4, 5],
  13. curVal: 2,
  14. index: 1,
  15. preVal: 1
  16. }
  17. [object Object] {
  18. array: [1, 2, 3, 4, 5],
  19. curVal: 3,
  20. index: 2,
  21. preVal: 2
  22. }
  23. [object Object] {
  24. array: [1, 2, 3, 4, 5],
  25. curVal: 4,
  26. index: 3,
  27. preVal: 3
  28. }
  29. [object Object] {
  30. array: [1, 2, 3, 4, 5],
  31. curVal: 5,
  32. index: 4,
  33. preVal: 4
  34. }
  35.  
  36. */

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:

  1. var numbers = [1,2,3,4,5];
  2.  
  3. console.clear();
  4.  
  5. numbers.reduce(function(preVal, curVal, index, array){
  6. console.log({preVal, curVal, index, array});
  7. });
  8.  
  9. /*
  10. [object Object] {
  11. array: [1, 2, 3, 4, 5],
  12. curVal: 2,
  13. index: 1,
  14. preVal: 1
  15. }
  16. [object Object] {
  17. array: [1, 2, 3, 4, 5],
  18. curVal: 3,
  19. index: 2,
  20. preVal: undefined
  21. }
  22. [object Object] {
  23. array: [1, 2, 3, 4, 5],
  24. curVal: 4,
  25. index: 3,
  26. preVal: undefined
  27. }
  28. [object Object] {
  29. array: [1, 2, 3, 4, 5],
  30. curVal: 5,
  31. index: 4,
  32. preVal: undefined
  33. }
  34. */

You can give another parameter to let it start from the first element of the array:

  1. numbers.reduce(function(preVal, curVal, index, array){
  2. console.log({preVal, curVal, index, array});
  3. return curVal;
  4. }, "start");
  5.  
  6. /**
  7. [object Object] {
  8. array: [1, 2, 3, 4, 5],
  9. curVal: 1,
  10. index: 0,
  11. preVal: "start"
  12. }
  13. [object Object] {
  14. array: [1, 2, 3, 4, 5],
  15. curVal: 2,
  16. index: 1,
  17. preVal: 1
  18. }
  19. ...
  20. ...
  21. */

Sum up an number of array:

  1. let numbers = [1,2,3,4,5];
  2.  
  3. console.clear();
  4.  
  5. var sum = numbers.reduce( (preVal, curVal) => preVal + curVal);
  6. console.log("sum: " + sum);
  7.  
  8. /*
  9. Sum: 15
  10. */

Example 2:

  1. let people = [
  2. {
  3. name: 'Joe mins',
  4. yearsExperience: 1,
  5. dapartment: 'IT'
  6. },
  7. {
  8. name: "Sally koral",
  9. yearsExperience: 15,
  10. dapartment: 'Engineering'
  11. },
  12. {
  13. name: "Bill Fork",
  14. yearsExperience: 5,
  15. dapartment: 'Engineering'
  16. },
  17. {
  18. name: 'Jane James',
  19. yearsExperience: 11,
  20. dapartment: 'Manager'
  21. },
  22. {
  23. name: 'Bob Super',
  24. yearsExperience: 9,
  25. dapartment: 'IT'
  26. },
  27. ];
  28.  
  29. console.clear();
  30.  
  31. var yearsExperience = people.reduce( (sum, curVal) => sum + curVal.yearsExperience, 0);
  32.  
  33. console.log(yearsExperience); //41

Group by object:

  1. let people = [
  2. {
  3. name: 'Joe mins',
  4. yearsExperience: 1,
  5. dapartment: 'IT'
  6. },
  7. {
  8. name: "Sally koral",
  9. yearsExperience: 15,
  10. dapartment: 'Engineering'
  11. },
  12. {
  13. name: "Bill Fork",
  14. yearsExperience: 5,
  15. dapartment: 'Engineering'
  16. },
  17. {
  18. name: 'Jane James',
  19. yearsExperience: 11,
  20. dapartment: 'Manager'
  21. },
  22. {
  23. name: 'Bob Super',
  24. yearsExperience: 9,
  25. dapartment: 'IT'
  26. },
  27. ];
  28.  
  29. console.clear();
  30.  
  31. var departmentExperienceYears = people.reduce( (groupByObject, employee) => {
  32. let dapartment = employee.dapartment;
  33. if(!groupByObject[dapartment]){
  34. groupByObject[dapartment] = 0;
  35. groupByObject[dapartment] += employee.yearsExperience;
  36. }
  37.  
  38. return groupByObject;
  39. }, {});
  40.  
  41. console.log(departmentExperienceYears);
  42.  
  43. /*
  44. [object Object] {
  45. Engineering: 15,
  46. IT: 1,
  47. Manager: 11
  48. }
  49. */

[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. webserver<1>

    1. 实现基础的信号处理 sigaction使用前一定内存清零 2. 实现基础的进程模型 wait 等待子进程结束 #include <stdio.h> #include <unis ...

  2. [HDOJ - 5208] Where is Bob 【DFS+按位贪心】

    题目链接:HDOJ - 5208 题目分析 使用按位贪心的思想,即从高位向低位枚举,尽量使这一位的答案为 1 . 我们使用 DFS ,每次就是对于  [l1, r1] [l2, r2] x  进行处理 ...

  3. Matlab绘图系列之高级绘图

    Matlab绘图系列之高级绘图 原帖地址: http://blog.163.com/enjoy_world/blog/static/115033832007865616218/ Matlab绘图 20 ...

  4. iOS内存管理系列之一:对象所有权与引用计数

    当一个所有者(owner,其本身可以是任何一个Objective-C对象)做了以下某个动作时,它拥有对一个对象的所有权(ownership): 1. 创建一个对象.包括使用任何名称中包含“alloc” ...

  5. XP系统VPN设置

    为了解除公司上网策略限制,或者为了上Google,Facebook,都可以通过设置VPN实现. 要使用VPN需要到VPN服务商注册,链接VPN服务商. ======================== ...

  6. Android假退出不是流氓行为

    转自Android假退出不是流氓行为 关于Android程序的退出,目前我们没有再用System.exit(0)或killProcess的机制而是直接用Activity.finish假退出了.因此在内 ...

  7. 字符串模式匹配算法——BM、Horspool、Sunday、KMP、KR、AC算法一网打尽

    字符串模式匹配算法——BM.Horspool.Sunday.KMP.KR.AC算法一网打尽 本文内容框架: §1 Boyer-Moore算法 §2 Horspool算法 §3 Sunday算法 §4 ...

  8. 子窗体显示在任务栏,且子窗体中又有弹窗(CreateParams修改三个风格参数)

    子窗体显示在任务栏时, procedure Tfrm_SendSmartMsg.CreateParams(var Params: TCreateParams);begin  inherited;  P ...

  9. BZOJ1699: [Usaco2007 Jan]Balanced Lineup排队

    1699: [Usaco2007 Jan]Balanced Lineup排队 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 933  Solved: 56 ...

  10. 2015第44周五Java集群技术(转)

    从http://blog.csdn.net/cdh1213/article/details/21443239上看到这篇文章,感觉很不错,找好久没找到中文出处,最早看是从http://www.these ...