JavaScript Array Methods: map, filter, reduce and More

JavaScript’s built-in array methods let you transform, search, and aggregate data without explicit loops. They’re immutable by design (they return a new array rather than mutating the original) and combine elegantly for data pipelines. Here’s a practical reference with real-world examples.

Problem: How do you transform, filter, and aggregate JavaScript arrays concisely without writing verbose for loops?

Solution: Use the built-in array methods — map() to transform each element, filter() to return a subset, reduce() to accumulate a value, find() / findIndex() for lookup, and some() / every() for boolean checks — all without mutating the original array.

const 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 — transform every element, returns a new array of the same length
const titles = posts.map( p => p.title );
// ['Hello World', 'About Flexbox', 'Draft Post', 'CSS Grid Guide']

// filter — keep only elements that pass the test
const published = posts.filter( p => p.published );
// 3 items (excludes the draft)

// reduce — accumulate a single value from all elements
const totalViews = posts.reduce( ( sum, p ) => sum + p.views, 0 );
// 2430

// find / findIndex — first match
const bigPost = posts.find( p => p.views > 1000 );
// { id: 1, title: 'Hello World', ... }

// some / every — boolean checks
const hasUnpublished = posts.some( p => ! p.published );  // true
const allPublished   = posts.every( p => p.published );   // false

// flat / flatMap — flatten nested arrays
const tags = [ ['css', 'layout'], ['grid'], ['flexbox', 'css'] ];
const uniqueTags = [ ...new Set( tags.flat() ) ];
// ['css', 'layout', 'grid', 'flexbox']

// Chaining — get titles of published posts sorted by views descending
const topTitles = posts
    .filter( p => p.published )
    .sort( ( a, b ) => b.views - a.views )
    .map( p => p.title );
// ['Hello World', 'CSS Grid Guide', 'About Flexbox']

A practical reduce example — group posts by a property:

const byStatus = posts.reduce( ( groups, post ) => {
    const key = post.published ? 'published' : 'draft';
    groups[ key ] = groups[ key ] || [];
    groups[ key ].push( post );
    return groups;
}, {} );
// { published: [...], draft: [...] }

NOTE: Array.prototype.sort() mutates the original array. If you need to keep the original order intact, sort a copy: [...posts].sort(...). Also note that the default sort compares elements as strings, which gives wrong results for numbers — always provide a comparator function.