Arrays & Modern Array Methods (map, filter, reduce)
1. Simple Definition
Array ek ordered list hoti hai jisme hum multiple values ko ek single variable ke andar zero-based indexing (0, 1, 2...) ke sath store karte hain. Modern JavaScript me arrays sirf values store nahi karte, balki functional methods (map, filter, reduce) se data ko transform, filter aur aggregate karne ki super-power dete hain.
2. Real-Life Analogy
• Array Index: Train ke dabbe (Coach 0, Coach 1, Coach 2).
• map(): Har passenger ko ek welcome drink serve karna (Har item par function chala kar naya array banana).
• filter(): Sirf un passengers ko filter karna jinke paas valid ticket ho (Condition match karne wale items nikalna).
• reduce(): Train ke sabhi passengers ka total luggage weight calculate karke single number me nikalna!
3. Why Do We Need It?
Real-world web apps 100% array data par chalti hain: YouTube videos ki list, Instagram feed ke posts, Amazon search ke products, aur WhatsApp messages ki chat history — sabhi arrays hain!
4. Syntax & Core Methods
const scores = [85, 92, 78, 95];
// 1. Mutating Methods (Original array change karte hain)
scores.push(99); // End me add karta hai
scores.pop(); // End se remove karta hai
scores.unshift(60); // Shuru me add karta hai
scores.shift(); // Shuru se remove karta hai
// 2. The Big Three Functional Methods (Return NEW array - Never mutate!)
// MAP: Transform each item
const doubled = scores.map(x => x * 2);
// FILTER: Keep items matching condition
const topScores = scores.filter(x => x >= 90);
// REDUCE: Accumulate into single total
const totalSum = scores.reduce((acc, curr) => acc + curr, 0);
5. Basic Example (E-Commerce Product Filter & Map)
const products = [
{ id: 1, name: "Mechanical Keyboard", price: 2500, inStock: true },
{ id: 2, name: "Gaming Mouse", price: 1200, inStock: false },
{ id: 3, name: "HD Monitor", price: 8500, inStock: true },
{ id: 4, name: "Mousepad", price: 400, inStock: true }
];
// Step 1: Filter in-stock items under ₹3000
const affordableInStock = products
.filter(p => p.inStock && p.price < 3000)
.map(p => `${p.name} - ₹${p.price}`);
console.log("Filtered Products:", affordableInStock);
6. Output / Expected Result
7. Code Explanation
.map(callback): Original array ki length ke barabar ek naya transformed array return karta hai..filter(callback): Callback jahantruereturn kare, sirf un items ko naye array me rakhta hai..reduce(callback, initialValue):acc(accumulator) me har step par running total jodte hue aakhri single value return karta hai..find(callback): Condition match karne wala pehla single item return karta hai..includes(value): Check karta hai ki array me wo value maujood hai ya nahi (returns boolean).
8. Real-World Example
Shopping cart me checkout screen par GST aur delivery charge jodkar final bill amount calculate karne ke liye cart.reduce((total, item) => total + item.price, 0) use hota hai.
9. Common Mistakes: slice() vs splice()
• slice(start, end): Original array ko chhue bina uska ek chota piece copy karke return karta hai (Safe & Immutable!).
• splice(start, count): Original array ko cut kar deta hai aur modify karta hai! Production me bina soche splice use karne se data loss bugs aate hain.
10. Best Practices
- Modern JavaScript (React, Vue, Clean JS) me Immutability follow karein: original array ko mutate karne ke badle
map,filteraur[...spread]use karein. - Array sorting ke liye ES2023 ka modern
arr.toSorted()use karein jo original array ko mutate nahi karta.
11. Try It Yourself
Playground me numbers array [10, 20, 30, 40] par .map(x => x + 5) chala kar dekhein.
12. Challenge
Ek prices array [100, 250, 400, 50] ka reduce() use karke average price calculate karein.
13. Interview Questions
Answer: map() transform karke ek naya array return karta hai jisko aap aage chain kar sakte hain. Jabki forEach() hamesha undefined return karta hai aur sirf side-effects (jaise console.log) perform karne ke liye hota hai.
14. Quick Revision
- 0-indexed list of values.
maptransforms;filterselects;reduceaggregates.slicedoes not mutate;splicemutates.
15. FAQ
Q1. some() aur every() me kya fark hai?
some() true return karta hai agar kam se kam 1 item condition match kare. every() tabhi true return karta hai jab sabhi 100% items match karein.
Q2. Array ka aakhri element modern JS me kaise nikaalte hain?
ES2022 method: arr.at(-1) (purane arr[arr.length - 1] se 10 guna clean!).
Q3. Array me se duplicates kaise hatayein?
Set use karke: const unique = [...new Set(myArray)];.
Q4. flat() method kya karta hai?
Nested arrays (e.g. [1, [2, 3]]) ko flat single array [1, 2, 3] me convert karta hai.
Q5. Array.from() kab use karte hain?
DOM NodeLists ya string ko real JavaScript Array me convert karne ke liye taaki .map() use kar sakein.
Arrays & Modern Array Methods (map, filter, reduce)
1. Simple Definition
An Array is an ordered list of values stored at sequential numeric index positions starting at 0. Modern JavaScript provides powerful declarative array methods (map, filter, reduce, find, some, every) that manipulate data immutably without manual loop counters.
2. Real-Life Analogy
• map: Painting every car on the conveyor belt silver (transforms every item).
• filter: Security inspector allowing only cars with zero defects to proceed (selects subset).
• reduce: Weighing station calculating total combined mass of all assembled vehicles into a single number!
3. The Big Three: map, filter, reduce
const products = [
{ name: "Keyboard", price: 1200, inStock: true },
{ name: "Mouse", price: 600, inStock: false },
{ name: "Monitor", price: 15000, inStock: true }
];
// 1. filter: Select available products
const availableProducts = products.filter(item => item.inStock);
// 2. map: Extract product names into clean string array
const productNames = products.map(item => item.name);
// 3. reduce: Calculate total cart valuation
const totalPrice = availableProducts.reduce((sum, item) => sum + item.price, 0);
console.log("Cart Total:", totalPrice); // 16200
4. Mutating vs Non-Mutating Methods
| Type | Methods | Behavior |
|---|---|---|
| Mutating (Modifies original) | push(), pop(), splice(), sort() |
Modifies the array directly in place. |
| Non-Mutating (Pure) | map(), filter(), slice(), toSorted() |
Returns a brand new array without altering original. |
5. Common Mistakes
If you write curly braces products.map(p => { p.price * 2 }) without an explicit return, the new array fills with undefined! Use implicit return p => p.price * 2 or add return explicitly.
6. Best Practices
- Prefer non-mutating functional methods (
map,filter) over stateful mutations. - Always provide an initial accumulator value to
reduce()(e.g.0or[]). - Use
find()when you only need a single matching element instead of filtering entire arrays.
7. Practice Exercise
Given an array of scores [45, 82, 90, 63, 71, 38], filter only passing marks (>= 50) and calculate the average score using reduce().
8. Interview Questions
Answer: map() allocates memory and returns a new transformed array of identical length. forEach() executes a callback for side effects on each element and returns undefined.
9. Summary / Cheat Card
maptransforms each item (1:1 output).filterincludes or excludes items based on boolean test.reduceaccumulates collection down to a single value.findreturns first match;somechecks if any match.
10. FAQ
Q1. Can you chain array methods together?
Yes! items.filter(...).map(...).sort(...) is standard functional programming syntax.