博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Javascript] Introducing Reduce: Common Patterns
阅读量:5088 次
发布时间:2019-06-13

本文共 1398 字,大约阅读时间需要 4 分钟。

Learn how two common array functions - map() and filter() - are syntactic sugar for reduce operations. Learn how to use them, how to compose them, and how using reduce can give you a big performance boost over composing filters and maps over a large data set.

 

var data = [1, 2, 3];var doubled = data.reduce(function(acc, value) {  acc.push(value * 2);  return acc;}, []);var doubleMapped = data.map(function(item) {  return item * 2;});var data2 = [1, 2, 3, 4, 5, 6];var evens = data2.reduce(function(acc, value) {  if (value % 2 === 0) {    acc.push(value);  }  return acc;}, []);var evenFiltered = data2.filter(function(item) {  return (item % 2 === 0);});var filterMapped = data2.filter(function(value) {  return value % 2 === 0;}).map(function(value) {  return value * 2;});

 

About big data:

var bigData = [];for (var i = 0; i < 1000000; i++) {  bigData[i] = i; } console.time('bigData');var filterMappedBigData = bigData.filter(function(value) {  return value % 2 === 0;}).map(function(value) {  return value * 2;});console.timeEnd('bigData');  //79ms console.time('bigDataReduce');var reducedBigData = bigData.reduce(function(acc, value) {  if (value % 2 === 0) {    acc.push(value * 2);  }  return acc;}, []); console.timeEnd('bigDataReduce'); //54ms

Because map and filter each will go thought the array, but reduce only go thought once.

 

转载于:https://www.cnblogs.com/Answer1215/p/5005110.html

你可能感兴趣的文章
构建之法阅读笔记01
查看>>
Item 2:Prefer C++-style casts.(More Effective C++)
查看>>
Delegation and Core Location(Chapter 4 of iOS Programming: The Big Nerd Ranch Guide)
查看>>
HDU 4001 To Miss Our Children Time dp
查看>>
mina 通讯框架
查看>>
vue表格业务
查看>>
maven 配置说明
查看>>
js接收网页参数
查看>>
linux之查看端口占用
查看>>
[原创]浅谈互联网金融测试平台规划
查看>>
什么是网关及网关作用(转)
查看>>
skymvc网站测试之mysql数据生成
查看>>
Asp.Net Core WebApi 和Asp.Net WebApi上传文件
查看>>
android脚步---如何看log之程序停止运行,和UI线程和非UI线程之间切换
查看>>
循环结构反思
查看>>
『TensorFlow』SSD源码学习_其一:论文及开源项目文档介绍
查看>>
EasyUI的时间控件禁止输入
查看>>
js 判断浏览器类型
查看>>
Easyui后台管理角色权限控制
查看>>
js函数模拟实现a标签的点击实现href
查看>>