JavaScript array methods: map, filter, reduce and more
Lists of posts from the REST API, products in a cart, form fields: front-end code works with arrays all the time. The built-in array methods transform, search and sum them without hand-written for loops, and they can be chained into short, readable pipelines.
Problem: Loops that build new arrays, count totals and search for items take many lines and are easy to get wrong.
Solution: Use map() to transform every item, filter() to keep some of them, reduce() to calculate one value, find() to get the first match and some() / every() for yes/no checks. These methods return new values and do not change the original array.
The data
var posts = [
{ id: 1, title: 'Hello World', views: 1200, published: true },
{ id: 2, title: 'About Flexbox', views: 340, published: true },
{ id: 3, title: 'Draft Post', views: 0, published: false },
{ id: 4, title: 'CSS Grid Guide', views: 890, published: true }
];
map, filter, reduce
// map: a new array of the same length
var titles = posts.map( function ( p ) { return p.title; } );
// ['Hello World', 'About Flexbox', 'Draft Post', 'CSS Grid Guide']
// filter: only the items for which the function returns true
var published = posts.filter( function ( p ) { return p.published; } );
// 3 items
// reduce: one value from all items; the second argument is the start value
var totalViews = posts.reduce( function ( sum, p ) { return sum + p.views; }, 0 );
// 2430
With arrow functions (all current browsers, not Internet Explorer) the same is shorter: posts.map( p => p.title ).
find, some, every
var popular = posts.find( function ( p ) { return p.views > 1000; } ); // the first match or undefined
var index = posts.findIndex( function ( p ) { return p.id === 3; } ); // 2, or -1
var hasDrafts = posts.some( function ( p ) { return ! p.published; } ); // true
var allPublished = posts.every( function ( p ) { return p.published; } ); // false
Chaining
Titles of the published posts, most viewed first:
var top = posts
.filter( function ( p ) { return p.published; } )
.sort( function ( a, b ) { return b.views - a.views; } )
.map( function ( p ) { return p.title; } );
// ['Hello World', 'CSS Grid Guide', 'About Flexbox']
Here sort() is safe because filter() already returned a new array.
Grouping with reduce
var byStatus = posts.reduce( function ( groups, post ) {
var key = post.published ? 'published' : 'draft';
( groups[ key ] = groups[ key ] || [] ).push( post );
return groups;
}, {} );
// { published: [...], draft: [...] }
flat
Arrays of arrays, for example the tags of several posts, are flattened with flat() (new in ES2019: Chrome 69, Firefox 62, Safari 12; not in Edge and IE yet). Together with Set it removes duplicates:
var tags = [ [ 'css', 'layout' ], [ 'grid' ], [ 'flexbox', 'css' ] ]; var unique = Array.from( new Set( tags.flat() ) ); // ['css', 'layout', 'grid', 'flexbox']
For older browsers use [].concat.apply( [], tags ) instead of tags.flat().
NOTE: sort() is the exception: it changes the original array. Sort a copy (posts.slice().sort(...)) when the original order is still needed, and always pass a compare function for numbers: without it the items are compared as strings, and 100 comes before 20.