📘 Lesson · Lesson 28
Array Iteration: map, filter, reduce
Array Iteration: map, filter, reduce
The Big Idea — passing functions to functions
let marks = [85, 92, 78];
// Instead of writing a loop yourself...
for (let i = 0; i < marks.length; i++) { console.log(marks[i]); }
// ...you hand a FUNCTION to the array method, and it does the looping:
marks.forEach(m => console.log(m));
These methods take a function as an argument — a "callback" — and run it once for every item in the array. You no longer write the loop machinery (counter, condition, index); you simply describe what to do with each item. This is a major shift in how you think about arrays, and it produces shorter, clearer code that says WHAT you want rather than HOW to loop. The three you must know are
map, filter, and reduce. They appear in every modern JavaScript codebase and in nearly every interview.forEach — do something with each item
let students = ["Aman", "Priya"];
students.forEach(name => console.log("Hello " + name));
// Hello Aman
// Hello Priya
// It can also give you the index:
students.forEach((name, index) => console.log(index, name));
let result = students.forEach(n => n); // undefined — forEach returns NOTHING
forEach() simply runs your function once per item — it's a cleaner replacement for a basic for loop. The callback receives each item (and optionally its index). Crucially, forEach returns undefined: it produces no new array. Use it when you want to DO something with each item (print it, add it to the page) rather than to BUILD something from the items. If you find yourself pushing results into a new array inside a forEach, you almost certainly want map instead.map — transform every item into a new array
let marks = [40, 50, 60];
let doubled = marks.map(m => m * 2); // [80, 100, 120]
let percent = marks.map(m => m + "%"); // ["40%", "50%", "60%"]
console.log(marks); // [40,50,60] ← original unchanged
// Very common in real code — building HTML from data:
let names = ["Aman", "Priya"];
let listItems = names.map(n => `${n} `);
map() creates a NEW array by transforming every item — the new array always has the SAME length as the original. Whatever your callback returns becomes the item at that position. Think of it as a conveyor belt: each item goes in, a changed version comes out. It's the go-to method for converting data into another shape — numbers into formatted strings, raw data into HTML snippets, objects into just their names. Remember: map = transform, one-in-one-out. Original untouched.filter — select the items you want
let marks = [85, 20, 92, 15];
let passed = marks.filter(m => m >= 33); // [85, 92]
let failed = marks.filter(m => m < 33); // [20, 15]
let words = ["hi", "hello", "hey"];
let long = words.filter(w => w.length > 2); // ["hello", "hey"]
filter() creates a NEW array containing only the items for which your callback returns true. Your function acts as a test: return true to keep the item, false to drop it. Unlike map, the resulting array is usually SHORTER (it can even be empty). This is how you search, filter search results, remove invalid entries, or split data into categories. The distinction to hold onto: map CHANGES each item and keeps the count; filter KEEPS items unchanged but reduces the count.reduce — boil an array down to a single value
let marks = [10, 20, 30];
let total = marks.reduce((sum, m) => sum + m, 0); // 60
// ↑ ↑ ↑
// accumulator current starting value
// Step by step: sum=0,m=10 → 10; sum=10,m=20 → 30; sum=30,m=30 → 60
let max = marks.reduce((a, b) => a > b ? a : b); // 30
let avg = total / marks.length; // 20
reduce() combines all items into ONE value — a sum, a maximum, a merged object. Its callback takes two key arguments: the accumulator (the running result so far) and the current item. Whatever you return becomes the accumulator for the next round. The second argument to reduce is the STARTING value (usually 0 for sums). It's the hardest of the three to grasp, so trace the comments above line by line. Its classic use is totalling a cart, summing marks, or counting occurrences. map transforms, filter selects, reduce combines — remember that trio and you have the heart of modern array work.Exam Corner
Q: What does map() return? A new array of the same length with each item transformed.
Q: What does filter() return? A new array with only the items whose callback returned true.
Q: What does reduce() return? A single value built up from all the items.
Q: What does forEach() return? undefined — it's for side effects, not building arrays.
Q: Sum an array of numbers using reduce.
Q: What does filter() return? A new array with only the items whose callback returned true.
Q: What does reduce() return? A single value built up from all the items.
Q: What does forEach() return? undefined — it's for side effects, not building arrays.
Q: Sum an array of numbers using reduce.
arr.reduce((sum, n) => sum + n, 0)
मुख्य विचार — functions को functions में भेजना
let marks = [85, 92, 78];
// Khud loop likhne ke bajaye...
for (let i = 0; i < marks.length; i++) { console.log(marks[i]); }
// ...aap array method ko FUNCTION dete hain, aur vah looping karta hai:
marks.forEach(m => console.log(m));
ये methods function को argument के रूप में लेते हैं — "callback" — और उसे array के हर item के लिए एक बार चलाते हैं. आप अब loop machinery (counter, condition, index) नहीं लिखते; आप बस बताते हैं हर item के साथ क्या करना है. यह arrays के बारे में सोचने में बड़ा बदलाव है, और छोटा, साफ code बनाता है जो कहता है आप KYA चाहते हैं न कि KAISE loop करें. तीन जो आपको ज़रूर जानने चाहिए:
map, filter, और reduce. वे हर modern JavaScript codebase में और लगभग हर interview में आते हैं.forEach — हर item के साथ कुछ करो
let students = ["Aman", "Priya"];
students.forEach(name => console.log("Hello " + name));
// Hello Aman
// Hello Priya
// Yeh index bhi de sakta hai:
students.forEach((name, index) => console.log(index, name));
let result = students.forEach(n => n); // undefined — forEach KUCH NAHI lautata
forEach() बस आपका function हर item के लिए एक बार चलाता है — यह basic for loop का साफ विकल्प है. Callback को हर item मिलता है (और वैकल्पिक रूप से उसका index). अहम बात, forEach undefined लौटाता है: यह कोई नई array नहीं बनाता. इसे तब use कीजिए जब हर item के साथ कुछ KARNA हो (print करना, page में जोड़ना) न कि items से कुछ BANANA हो. अगर आप खुद को forEach के अंदर नई array में results push करते पाएं, आपको लगभग निश्चित रूप से map चाहिए.map — हर item को नई array में बदलो
let marks = [40, 50, 60];
let doubled = marks.map(m => m * 2); // [80, 100, 120]
let percent = marks.map(m => m + "%"); // ["40%", "50%", "60%"]
console.log(marks); // [40,50,60] ← original anbadla
// Asli code me bahut common — data se HTML banana:
let names = ["Aman", "Priya"];
let listItems = names.map(n => `${n} `);
map() हर item को बदलकर NAYI array बनाता है — नई array की length हमेशा मूल जितनी ही होती है. आपका callback जो लौटाए वह उस position का item बनता है. इसे conveyor belt समझिए: हर item अंदर जाता है, बदला हुआ बाहर आता है. यह data को दूसरे आकार में बदलने का पसंदीदा method है — numbers को formatted strings में, कच्चे data को HTML टुकड़ों में, objects को सिर्फ उनके नामों में. याद रखिए: map = transform, एक अंदर-एक बाहर. मूल अछूता.filter — जो items चाहिए वही चुनो
let marks = [85, 20, 92, 15];
let passed = marks.filter(m => m >= 33); // [85, 92]
let failed = marks.filter(m => m < 33); // [20, 15]
let words = ["hi", "hello", "hey"];
let long = words.filter(w => w.length > 2); // ["hello", "hey"]
filter() NAYI array बनाता है जिसमें सिर्फ वे items हैं जिनके लिए आपका callback true लौटाता है. आपका function test का काम करता है: item रखने को true, हटाने को false लौटाइए. map के उलट, नतीजा array आमतौर पर CHHOTI होती है (खाली भी हो सकती है). ऐसे ही आप खोजते हैं, search results filter करते, अमान्य entries हटाते, या data को श्रेणियों में बांटते हैं. पकड़ने लायक भेद: map हर item BADALTA है और गिनती रखता है; filter items अनबदले RAKHTA है पर गिनती घटाता है.reduce — array को एक value में समेटो
let marks = [10, 20, 30];
let total = marks.reduce((sum, m) => sum + m, 0); // 60
// ↑ ↑ ↑
// accumulator current shuruati value
// Kadam dar kadam: sum=0,m=10 → 10; sum=10,m=20 → 30; sum=30,m=30 → 60
let max = marks.reduce((a, b) => a > b ? a : b); // 30
let avg = total / marks.length; // 20
reduce() सारे items को EK value में मिलाता है — योग, अधिकतम, मिला हुआ object. इसका callback दो मुख्य arguments लेता है: accumulator (अब तक का चलता नतीजा) और current item. आप जो लौटाएं वह अगले दौर का accumulator बनता है. reduce का दूसरा argument SHURUATI value है (योग के लिए आमतौर पर 0). तीनों में यह समझने में सबसे मुश्किल है, तो ऊपर की comments line-दर-line देखिए. इसका classic इस्तेमाल cart का total, marks का योग, या occurrences गिनना है. map बदलता है, filter चुनता है, reduce मिलाता है — वह तिकड़ी याद रखिए और आपके पास modern array काम का दिल है.Exam Corner
Q: map() क्या लौटाता है? उतनी ही length की नई array जिसमें हर item बदला हुआ.
Q: filter() क्या लौटाता है? नई array जिसमें सिर्फ वे items जिनके callback ने true लौटाया.
Q: reduce() क्या लौटाता है? सारे items से बनी एक value.
Q: forEach() क्या लौटाता है? undefined — यह side effects के लिए है, arrays बनाने को नहीं.
Q: reduce से numbers की array जोड़िए.
Q: filter() क्या लौटाता है? नई array जिसमें सिर्फ वे items जिनके callback ने true लौटाया.
Q: reduce() क्या लौटाता है? सारे items से बनी एक value.
Q: forEach() क्या लौटाता है? undefined — यह side effects के लिए है, arrays बनाने को नहीं.
Q: reduce से numbers की array जोड़िए.
arr.reduce((sum, n) => sum + n, 0)
💻 Live Code Editor
इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का
console.log देखने के लिए F12 दबाइए.