JavaScript Functional Programming — map, filter and reduce

Bojan Gvozderac
Oct 24, 2017 · 6 min read

Description:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Example:

const numbers = [2, 4, 8, 10];
const halves = numbers.map(x => x / 2);
// halves is [1, 2, 4, 5]

Description:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Example:

const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];

const longWords = words.filter(word => word.length > 6);
// longWords is ["exuberant", "destruction", "present"]

Description:

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Example:

const total = [0, 1, 2, 3].reduce((sum, value) => sum + value, 1);// total is 7

Compose Functions

const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);

Example usage:

const add1 = n => n + 1;
const double = n => n * 2;
const add1ThenDouble = compose(
double,
add1
);
add1ThenDouble(2); // 6
// ((2 + 1 = 3) * 2 = 6)

Awesome!

Chaining Promises

let itemIDs = [1, 2, 3, 4, 5]; itemIDs.reduce((promise, itemID) => {
return promise.then(_ => api.deleteItem(itemID));
}, Promise.resolve());
Promise.resolve()
.then(_ => api.deleteItem(1))
.then(_ => api.deleteItem(2))
.then(_ => api.deleteItem(3))
.then(_ => api.deleteItem(4))
.then(_ => api.deleteItem(5));

Call to Action

We saw some really cool and creative uses of map, filter and reduce… who are we shitting here? The cool and creative examples were only for reduce but never mind that!
If you’ve stumbled upon some interesting ways map, filter or reduce were used be sure to put it in the comments, I’m sure there are heaps of practical ways these 3 can be used!

JSGuru

This blog is assembled out of pure love for developing and designing mobile and web applications!

Thanks to Slobodan Kelecevic and Srdjan Sukara.

Bojan Gvozderac

Written by

bojangvozderac.com | Senior Front End Developer @ werkspot.nl

JSGuru

JSGuru

This blog is assembled out of pure love for developing and designing mobile and web applications!