JavaScript Array Methods
Master the most important tools in modern JavaScript & React: `map`, `filter`, `reduce`, `find`, and method chaining.
1. The Holy Trinity: `map()`, `filter()`, `reduce()`
Instead of writing long manual for loops, modern JavaScript uses these 3 functions to transform data cleanly:
💡 Think of a Factory Assembly Line
- `map()` (Transform): Takes every raw item on the belt and paints it (transforms every item).
- `filter()` (Select): The quality inspector that keeps only items meeting your standard.
- `reduce()` (Combine): Takes all finished products and packs them into a single final shipping box.
const products = [
{ name: "Phone", price: 800, inStock: true },
{ name: "Laptop", price: 1500, inStock: false },
{ name: "Mouse", price: 50, inStock: true }
];
// 1. map(): Pull out all product names
const names = products.map(p => p.name);
console.log("Names:", names);
// 2. filter(): Keep only items that are in stock
const available = products.filter(p => p.inStock);
console.log("Available:", available);
// 3. reduce(): Calculate the total price of all items
const totalPrice = products.reduce((sum, p) => sum + p.price, 0);
console.log("Total Price: $" + totalPrice);
Names: [ 'Phone', 'Laptop', 'Mouse' ]
Available: [ { name: 'Phone', price: 800, inStock: true }, { name: 'Mouse', price: 50, inStock: true } ]
Total Price: $2350
2. `find()` vs `filter()`: Grabbing One vs Many
A common beginner trap is using filter when they only want a single matching item:
`find()` (Grabs ONE Item 🎯)
Stops searching on the first match and returns the exact item (or undefined).
const user = users.find(u => u.id === 101);
// Returns: { id: 101, name: "Alex" }
`filter()` (Grabs a LIST 📦)
Searches the whole array and always returns a new array list of all matches.
const active = users.filter(u => u.active);
// Returns: [{ id: 101 }, { id: 102 }]
3. The Array `sort()` Gotcha (Alphabetical by Default)
By default, JavaScript's .sort() converts numbers into words (strings) and compares them alphabetically. That means "10" comes before "2"!
const scores = [10, 5, 40, 25, 2];
// ❌ Default sort compares as strings:
console.log([...scores].sort()); // [10, 2, 25, 40, 5] 😱
// ✅ Correct numerical sort with comparator (a - b):
const ascending = [...scores].sort((a, b) => a - b);
console.log("Ascending:", ascending); // [2, 5, 10, 25, 40]
// ✅ Descending sort with comparator (b - a):
const descending = [...scores].sort((a, b) => b - a);
console.log("Descending:", descending); // [40, 25, 10, 5, 2]
[ 10, 2, 25, 40, 5 ] Ascending: [ 2, 5, 10, 25, 40 ] Descending: [ 40, 25, 10, 5, 2 ]
4. Method Chaining: Creating Data Pipelines
Because methods like filter() and map() return new arrays, you can chain them together into clean, readable single-line pipelines:
const cart = [
{ title: "Laptop", price: 1200, category: "Tech" },
{ title: "Shirt", price: 40, category: "Clothing" },
{ title: "Monitor", price: 300, category: "Tech" },
{ title: "Shoes", price: 80, category: "Clothing" }
];
// Calculate total cost of only "Tech" items with 10% discount:
const discountedTechTotal = cart
.filter(item => item.category === "Tech")
.map(item => item.price * 0.9)
.reduce((sum, price) => sum + price, 0);
console.log("Total Tech Total with Discount: $" + discountedTechTotal);
Total Tech Total with Discount: $1350
5. Quick Array Methods Guide
| Method | What it Returns | Changes Original? | Purpose |
|---|---|---|---|
arr.map(fn) |
New array (same length) | No (Safe) | Transform every element |
arr.filter(fn) |
New array (subset of matches) | No (Safe) | Select matching elements |
arr.reduce(fn, init) |
Single accumulated value | No (Safe) | Total, group, or merge |
arr.find(fn) |
First matching element or undefined |
No (Safe) | Search for a single item |
arr.sort((a,b) => a-b) |
Same array sorted | Yes (Mutates) | Sorts numbers numerically |
6. Array Methods Interview Deck
Test your knowledge on map vs filter returns, reduce accumulation, sorting traps, find behavior, and chaining:
7. Practice Challenge
🎯 Coding Challenge: Cart Pipeline Chaining
Use method chaining (filter -> map -> reduce) on a list of cart items to calculate the total price of only items belonging to the "Tech" category.