[Javascript] Introducing Reduce: Common Patterns
JavaScript Common reduce Patterns
2023-09-14 08:59:20 时间
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.
相关文章
- javascript 判断变量是否是数组(Array)
- [Javascript] Filter out Duplicates from Flat JavaScript Array with array.filter / reduce / Set
- [Javascript] Safely Access a Property on a JavaScript Array with Optional Chaining
- [Javascript] Create an Async Generator and Loop Through Generated Promises with "For Await Of" Loops
- [Javascript] Create Your First Iterator in JavaScript
- [Javascript] Use requestIdleCallback to schedule JavaScript tasks at an optimal time
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- [Poi] Build and Analyze Your JavaScript Bundles with Poi
- [REASONML] Using Javascript npm package from REASON
- [Javascript] An Introduction to JSPM (JavaScript Package Manager)
- 小白学 Python 爬虫(39): JavaScript 渲染服务 scrapy-splash 入门
- [Javascript] Wait for the Fastest JavaScript Promise to Be Fulfilled with Promise.any()
- [Javascript] Create an Image with JavaScript Using Fetch and URL.createObjectURL
- [Javascript] Understanding the .constructor property on JavaScript Objects
- [Javascript] Introducing Reduce: Common Patterns
- [Javascript] An Introduction to JSPM (JavaScript Package Manager)
- javascript面向对象之Javascript 继承
- JavaScript 中搜索数组的四种方法
- SAP Server Side JavaScript解决方案
- Atitit maven 常见类库配置法 maven common lib jar v2 t88 目录 1. Express DSL COMMON2 1.1. Ognl2 1.2. veloci
- Atitit.js模块化 atiImport 的新特性javascript import
- 从零开始学_JavaScript_系列(26)——只需要前端知识的ajax教程
- 【JavaScript】出现即使设置了ID也获取不到的可能原因与window.onload
- Handsontable 12.3.0 JavaScript 数据网格组件 -Crack