[Javascript] Introducing Reduce: Common Patterns
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.