JavaScript Array Methods: Map and Filter Explained
Master JavaScript's ES6 array helper methods map() and filter() with practical examples. Learn how to transform and filter arrays like a pro.
Moshiour Rahman
Advertisement
Overview
map(), reduce(), and filter() are powerful array helper methods in JavaScript. Each one iterates over an array and performs a transformation or computation, returning a new array based on the result. In this article, you’ll learn why and how to use map() and filter() effectively.
Quick Visual Summary
Here’s how these methods work at a glance:
- map() - Transform each element → returns new array of same length
- filter() - Keep elements that pass a test → returns new array (potentially shorter)
- reduce() - Accumulate values → returns single value
Array.map()
The map() method creates a new array by calling a function on every element of the original array.
Syntax
const newArray = arr.map(function callback(element, index, array) {
// return element for new_array
});
In the callback, only the array element is required. Usually, some action is performed on the value and then a new value is returned.
Example 1: Double Each Number
const numbers = [1, 4, 9, 16];
// Using arrow function for cleaner syntax
const doubled = numbers.map(x => x * 2);
console.log(doubled);
// Output: [2, 8, 18, 32]
console.log(numbers);
// Output: [1, 4, 9, 16] - Original array is unchanged!
Key Points:
- The original
numbersarray remains unchanged map()always returns a new array
Example 2: Reformatting Array Objects
When you need to modify an array of objects, map() is your best friend. Here’s how to iterate through objects and add new properties:
const owls = [
{ name: 'Great horned owl', likes: 'meat' },
{ name: 'Barn Owl', likes: 'fish' },
{ name: 'Snowy Owl', likes: 'fruits' },
{ name: 'Barred Owl', likes: 'mice' }
];
const owlsWithAge = owls.map(owl => ({
name: owl.name,
likes: owl.likes,
age: owl.name.length // Calculate age based on name length
}));
console.log(owlsWithAge);
// Output:
// [
// { name: 'Great horned owl', likes: 'meat', age: 16 },
// { name: 'Barn Owl', likes: 'fish', age: 8 },
// { name: 'Snowy Owl', likes: 'fruits', age: 9 },
// { name: 'Barred Owl', likes: 'mice', age: 10 }
// ]
Example 3: Rendering Lists in React
map() is extensively used in React for rendering lists:
import React from 'react';
const owls = ['Great horned owl', 'Barn Owl', 'Snowy Owl', 'Barred Owl'];
function OwlList() {
return (
<ul>
{owls.map(name => (
<li key={name}>{name}</li>
))}
</ul>
);
}
export default OwlList;
Array.filter()
The filter() method creates a new array with only elements that pass a test you provide as a callback function.
Important: filter() does not mutate the original array.
Example 1: Filtering Even Numbers
function isEven(value) {
return value % 2 === 0;
}
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
const evenNumbers = numbers.filter(isEven);
console.log(evenNumbers);
// Output: [2, 4, 6, 8, 10, 12]
Or using an arrow function:
const evenNumbers = numbers.filter(num => num % 2 === 0);
Example 2: Search Filter
Create a search function that filters items based on a query:
const owls = ['Great horned owl', 'Barn Owl', 'Snowy Owl', 'Barred Owl'];
const filterBySearch = (arr, query) => {
return arr.filter(item =>
item.toLowerCase().includes(query.toLowerCase())
);
};
console.log(filterBySearch(owls, 'Ba'));
// Output: ['Barn Owl', 'Barred Owl']
Example 3: Filter Objects by Property
const owls = [
{ name: 'Great horned owl', color: 'white' },
{ name: 'Barn Owl', color: 'brown' },
{ name: 'Snowy Owl', color: 'white' },
{ name: 'Barred Owl', color: 'brown' }
];
const whiteOwls = owls.filter(owl => owl.color === 'white');
console.log(whiteOwls);
// Output:
// [
// { name: 'Great horned owl', color: 'white' },
// { name: 'Snowy Owl', color: 'white' }
// ]
Example 4: Remove Duplicates
Use filter() with indexOf() to remove duplicates:
const owlsDuplicate = [
'Great horned owl',
'Barn Owl',
'Snowy Owl',
'Barred Owl',
'Great horned owl',
'Barn Owl'
];
const uniqueOwls = owlsDuplicate.filter(
(owl, index) => owlsDuplicate.indexOf(owl) === index
);
console.log(uniqueOwls);
// Output: ['Great horned owl', 'Barn Owl', 'Snowy Owl', 'Barred Owl']
Pro Tip: You can also use ES6 Set for a cleaner approach:
const uniqueOwls = [...new Set(owlsDuplicate)];
// Or
const uniqueOwls = Array.from(new Set(owlsDuplicate));
Chaining map() and filter()
You can chain these methods for powerful data transformations:
const products = [
{ name: 'Laptop', price: 1000, inStock: true },
{ name: 'Phone', price: 500, inStock: false },
{ name: 'Tablet', price: 300, inStock: true },
{ name: 'Watch', price: 200, inStock: true }
];
// Get names of in-stock products under $500
const affordableInStock = products
.filter(product => product.inStock && product.price < 500)
.map(product => product.name);
console.log(affordableInStock);
// Output: ['Tablet', 'Watch']
Conclusion
We’ve explored how to use JavaScript’s ES6 array helpers Array.filter() and Array.map(). These methods are fundamental to functional programming in JavaScript and are used extensively in modern frameworks like React.
In a future post, we’ll dive deep into Array.reduce(), another powerful array method for accumulating values.
Key Takeaways:
map()transforms every element and returns a new array of the same lengthfilter()returns a new array with only elements that pass the test- Neither method mutates the original array
- Chain them together for complex data transformations
Advertisement
Moshiour Rahman
Software Architect & AI Engineer
Enterprise software architect with deep expertise in financial systems, distributed architecture, and AI-powered applications. Building large-scale systems at Fortune 500 companies. Specializing in LLM orchestration, multi-agent systems, and cloud-native solutions. I share battle-tested patterns from real enterprise projects.
Related Articles
JavaScript Primer: Essential Concepts
Master core JavaScript concepts including higher-order functions, arrow functions, closures, and the spread operator with practical examples.
JavaScriptTurborepo: High-Performance Monorepo Build System
Master Turborepo for monorepo management. Learn workspace setup, caching, pipelines, and build performant multi-package JavaScript projects.
JavaScriptReact Hooks Complete Guide: useState to Custom Hooks
Master all React hooks from basics to advanced. Learn useState, useEffect, useContext, useReducer, useMemo, useCallback, and create custom hooks.
Comments
Comments are powered by GitHub Discussions.
Configure Giscus at giscus.app to enable comments.