Array Methods: map, filter, reduce, find
JavaScript arrays come with powerful built‑in methods that allow you to transform, filter, reduce, and search data. These methods are functional, meaning they typically return a new array or value without mutating the original. In React, they are indispensable for rendering lists, filtering data, computing derived state, and more.
The map() method creates a new array by calling a provided function on every element in the calling array.
Syntax & Example
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8]
// Original array is unchanged
console.log(numbers); // [1, 2, 3, 4]
React Use Case – Rendering Lists
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
Important: When using map() in React, always provide a key prop for efficient updates.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Syntax & Example
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6] (unchanged)
React Use Case – Filtering Data
const [searchTerm, setSearchTerm] = useState('');
const filteredItems = items.filter(item =>
item.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<ul>
{filteredItems.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
);
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 – not necessarily an array.
Syntax & Example
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
// With initial value (optional)
const product = numbers.reduce((acc, curr) => acc * curr, 1);
console.log(product); // 24
More Complex Example – Grouping
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 21 }
];
const groupedByAge = people.reduce((acc, person) => {
const key = person.age;
if (!acc[key]) acc[key] = [];
acc[key].push(person);
return acc;
}, {});
console.log(groupedByAge);
// { '21': [{name:'Alice',age:21}, {name:'Charlie',age:21}], '25': [{name:'Bob',age:25}] }
React Use Case – Derived State
const cart = [
{ item: 'Apple', price: 0.5, qty: 2 },
{ item: 'Banana', price: 0.3, qty: 3 }
];
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
// total = 2*0.5 + 3*0.3 = 1.0 + 0.9 = 1.9
The find() method returns the first element in the array that satisfies the provided testing function. If no match, it returns undefined.
Syntax & Example
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const user = users.find(u => u.id === 2);
console.log(user); // { id: 2, name: 'Bob' }
// When no match
const notFound = users.find(u => u.id === 99);
console.log(notFound); // undefined
React Use Case – Finding a Selected Item
const [selectedId, setSelectedId] = useState(null);
const selectedItem = items.find(item => item.id === selectedId);
// Use selectedItem to display details
Tip: find() only returns the first matching element. Use filter() if you need all matches.
These methods can be chained for complex transformations.
const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
.filter(n => n % 2 === 0) // [2, 4, 6]
.map(n => n * 2) // [4, 8, 12]
.reduce((acc, n) => acc + n, 0); // 24
console.log(result); // 24
Performance Consideration
Chaining creates intermediate arrays, which is fine for most cases. For very large data, consider using reduce() alone to avoid multiple passes.
A typical React component might:
filter()to search or filter a list.map()to render the list.reduce()to compute totals or aggregated stats.find()to locate a specific object.
function ProductList({ products, searchTerm, selectedCategory }) {
const filtered = products.filter(product => {
const matchName = product.name.toLowerCase().includes(searchTerm.toLowerCase());
const matchCategory = selectedCategory ? product.category === selectedCategory : true;
return matchName && matchCategory;
});
const totalPrice = filtered.reduce((sum, p) => sum + p.price, 0);
return (
<div>
<h2>Total: ${totalPrice.toFixed(2)}</h2>
<ul>
{filtered.map(product => (
<li key={product.id}>{product.name} – ${product.price}</li>
))}
</ul>
</div>
);
}
map– transforms each element and returns a new array.filter– selects elements that pass a test and returns a new array.reduce– accumulates values into a single result (number, object, array, etc.).find– returns the first matching element.- All are immutable – they don't mutate the original array.
- In React, they are essential for rendering, filtering, and computing derived state.
Key Takeaway
"Mastering map, filter, reduce, and find gives you superpowers for manipulating data in JavaScript – and they're your best friends in React."
Happy coding!