Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🖱️ Days 8–14 – Data, DOM और Events  ·  दिन 08

दिन 8: map, filter, reduce, find और sort

⏱ 100 min📶 Intermediate🎯 100% self-study
दिन 8 / 30

✅ आज आप सीखेंगे

  • forEach बनाम map: करना बनाम बदलना
  • filter, find, findIndex, some, every
  • Totals, गिनती और grouping के लिए reduce
  • Objects के arrays को price, rating या name से sort करना
  • Methods को chain करके पढ़ने लायक data pipelines

🏢 असली दुनिया में

Mr. Sharma dashboard माँगते हैं: “सिर्फ़ stock वाली मिठाइयाँ price के क्रम में दिखाओ, कुल stock value के साथ, और बताओ कुछ कम तो नहीं हो रहा।” Loops से यह 40 lines है। map, filter और reduce से 6 पढ़ने लायक lines। ये methods लगभग हर JavaScript interview में पूछे जाते हैं और React code का दिल हैं।

forEach और map

JavaScript
const products = [
  { id: 1, name: 'Kaju Katli',   category: 'dry',  price: 900, rating: 4.8, stock: 25 },
  { id: 2, name: 'Malai Ghewar', category: 'milk', price: 650, rating: 4.7, stock: 8 },
  { id: 3, name: 'Rasmalai',     category: 'milk', price: 700, rating: 4.6, stock: 12 },
  { id: 4, name: 'Besan Ladoo',  category: 'dry',  price: 500, rating: 4.5, stock: 40 },
  { id: 5, name: 'Kalakand',     category: 'milk', price: 600, rating: 4.4, stock: 0 },
  { id: 6, name: 'Soan Papdi',   category: 'dry',  price: 380, rating: 4.1, stock: 60 },
];

products.forEach(p => console.log(`${p.id}. ${p.name}`));   // DO something for each – returns nothing

const names = products.map(p => p.name);                     // TRANSFORM each – returns a new array
const withGst = products.map(p => ({ name: p.name, price: Math.round(p.price * 1.05) }));
console.log(names);
console.log(withGst.slice(0, 2));
1. Kaju Katli 2. Malai Ghewar 3. Rasmalai 4. Besan Ladoo 5. Kalakand 6. Soan Papdi [ 'Kaju Katli', 'Malai Ghewar', 'Rasmalai', 'Besan Ladoo', 'Kalakand', 'Soan Papdi' ] [ { name: 'Kaju Katli', price: 945 }, { name: 'Malai Ghewar', price: 683 } ]
[🥮, 🍮, 🍬] input arraymap(fn) → हर item पर fn[₹, ₹, ₹] नया array – वही lengthoriginal array नहीं बदलता
map हमेशा उसी length का array लौटाता है

filter, find, some, every

JavaScript
const products = [
  { id: 1, name: 'Kaju Katli',   category: 'dry',  price: 900, rating: 4.8, stock: 25 },
  { id: 2, name: 'Malai Ghewar', category: 'milk', price: 650, rating: 4.7, stock: 8 },
  { id: 3, name: 'Rasmalai',     category: 'milk', price: 700, rating: 4.6, stock: 12 },
  { id: 4, name: 'Besan Ladoo',  category: 'dry',  price: 500, rating: 4.5, stock: 40 },
  { id: 5, name: 'Kalakand',     category: 'milk', price: 600, rating: 4.4, stock: 0 },
  { id: 6, name: 'Soan Papdi',   category: 'dry',  price: 380, rating: 4.1, stock: 60 },
];

const inStock = products.filter(p => p.stock > 0);
const milkSweets = products.filter(p => p.category === 'milk');
console.log(inStock.length, 'in stock;', milkSweets.map(p => p.name).join(', '));

const ghewar = products.find(p => p.name.includes('Ghewar'));      // first match or undefined
const index = products.findIndex(p => p.id === 5);
console.log(ghewar.price, index);

console.log('Any sold out?', products.some(p => p.stock === 0));
console.log('All rated 4+?', products.every(p => p.rating >= 4));
5 in stock; Malai Ghewar, Rasmalai, Kalakand 650 4 Any sold out? true All rated 4+? true
Methodलौटाता हैकब
map(fn)नया array, वही lengthबदलना: prices → labels, data → HTML
filter(fn)नया array, 0..n itemsमेल खाते items रखना: stock, category
find(fn)पहला मेल या undefinedid से एक product ढूँढना
findIndex(fn)Index या -1Item को उसी जगह बदलना/हटाना
some(fn)true/false – कम से कम एक“क्या कुछ sold out है?”
every(fn)true/false – सभी“क्या सब fields भरे हैं?”
reduce(fn, start)एक value (number, object…)Totals, गिनती, grouping
forEach(fn)undefinedसिर्फ़ side effects (logging, DOM updates)

reduce – कई values से एक

JavaScript
const products = [
  { id: 1, name: 'Kaju Katli',   category: 'dry',  price: 900, rating: 4.8, stock: 25 },
  { id: 2, name: 'Malai Ghewar', category: 'milk', price: 650, rating: 4.7, stock: 8 },
  { id: 3, name: 'Rasmalai',     category: 'milk', price: 700, rating: 4.6, stock: 12 },
  { id: 4, name: 'Besan Ladoo',  category: 'dry',  price: 500, rating: 4.5, stock: 40 },
  { id: 5, name: 'Kalakand',     category: 'milk', price: 600, rating: 4.4, stock: 0 },
  { id: 6, name: 'Soan Papdi',   category: 'dry',  price: 380, rating: 4.1, stock: 60 },
];

// reduce((accumulator, item) => newAccumulator, startValue)
const stockValue = products.reduce((sum, p) => sum + p.price * p.stock, 0);
console.log('Stock value: ₹' + stockValue.toLocaleString('en-IN'));

const countByCategory = products.reduce((acc, p) => {
  acc[p.category] = (acc[p.category] || 0) + 1;
  return acc;
}, {});
console.log(countByCategory);

const cheapest = products.reduce((min, p) => (p.price < min.price ? p : min));
console.log('Cheapest:', cheapest.name);

const cart = [{ id: 1, qty: 2 }, { id: 4, qty: 1.5 }];
const cartTotal = cart.reduce((sum, line) => sum + products.find(p => p.id === line.id).price * line.qty, 0);
console.log('Cart total: ₹' + cartTotal);
Stock value: ₹78,900 { dry: 3, milk: 3 } Cheapest: Soan Papdi Cart total: ₹2550
💡 reduce को हमेशा start value दें

दूसरे argument के बिना reduce पहले item को start मानता है, जो ख़ाली array पर crash करता है (“Reduce of empty array with no initial value”) और items objects हों तो गड़बड़ करता है। Sums के लिए 0, grouping के लिए {}, lists के लिए []।

Objects के arrays sort करना

JavaScript
const products = [
  { id: 1, name: 'Kaju Katli',   category: 'dry',  price: 900, rating: 4.8, stock: 25 },
  { id: 2, name: 'Malai Ghewar', category: 'milk', price: 650, rating: 4.7, stock: 8 },
  { id: 3, name: 'Rasmalai',     category: 'milk', price: 700, rating: 4.6, stock: 12 },
  { id: 4, name: 'Besan Ladoo',  category: 'dry',  price: 500, rating: 4.5, stock: 40 },
  { id: 5, name: 'Kalakand',     category: 'milk', price: 600, rating: 4.4, stock: 0 },
  { id: 6, name: 'Soan Papdi',   category: 'dry',  price: 380, rating: 4.1, stock: 60 },
];

const byPrice = [...products].sort((a, b) => a.price - b.price);
const byRating = [...products].sort((a, b) => b.rating - a.rating);
const byName = [...products].sort((a, b) => a.name.localeCompare(b.name));
console.log(byPrice.map(p => `${p.name} ₹${p.price}`).join(' < '));
console.log(byRating[0].name, 'is top rated');
console.log(byName.map(p => p.name)[0]);
Soan Papdi ₹380 < Besan Ladoo ₹500 < Kalakand ₹600 < Malai Ghewar ₹650 < Rasmalai ₹700 < Kaju Katli ₹900 Kaju Katli is top rated Besan Ladoo

Chaining: data pipeline

JavaScript
const products = [
  { id: 1, name: 'Kaju Katli',   category: 'dry',  price: 900, rating: 4.8, stock: 25 },
  { id: 2, name: 'Malai Ghewar', category: 'milk', price: 650, rating: 4.7, stock: 8 },
  { id: 3, name: 'Rasmalai',     category: 'milk', price: 700, rating: 4.6, stock: 12 },
  { id: 4, name: 'Besan Ladoo',  category: 'dry',  price: 500, rating: 4.5, stock: 40 },
  { id: 5, name: 'Kalakand',     category: 'milk', price: 600, rating: 4.4, stock: 0 },
  { id: 6, name: 'Soan Papdi',   category: 'dry',  price: 380, rating: 4.1, stock: 60 },
];

const report = products
  .filter(p => p.stock > 0)                       // 1. only available
  .sort((a, b) => a.price - b.price)              // 2. cheapest first
  .map(p => `${p.name.padEnd(13)} ₹${p.price}  ${p.stock < 10 ? '⚠️ low stock' : ''}`);   // 3. format

console.log(report.join('\n'));
Soan Papdi ₹380 Besan Ladoo ₹500 Malai Ghewar ₹650 ⚠️ low stock Rasmalai ₹700 Kaju Katli ₹900

असली task: live product filter

HTML + JavaScript
<input id="q" placeholder="Search sweets…" aria-label="Search">
<select id="cat" aria-label="Category"><option value="">All</option><option value="milk">Milk</option><option value="dry">Dry</option></select>
<select id="sort" aria-label="Sort"><option value="">Sort</option><option value="low">Price ↑</option><option value="high">Price ↓</option><option value="rating">Rating</option></select>
<p id="summary"></p>
<ul id="list"></ul>

<script>
const products = [
  { id: 1, name: 'Kaju Katli',   category: 'dry',  price: 900, rating: 4.8, stock: 25 },
  { id: 2, name: 'Malai Ghewar', category: 'milk', price: 650, rating: 4.7, stock: 8 },
  { id: 3, name: 'Rasmalai',     category: 'milk', price: 700, rating: 4.6, stock: 12 },
  { id: 4, name: 'Besan Ladoo',  category: 'dry',  price: 500, rating: 4.5, stock: 40 },
  { id: 5, name: 'Kalakand',     category: 'milk', price: 600, rating: 4.4, stock: 0 },
  { id: 6, name: 'Soan Papdi',   category: 'dry',  price: 380, rating: 4.1, stock: 60 },
];

function render() {
  const q = document.querySelector('#q').value.trim().toLowerCase();
  const cat = document.querySelector('#cat').value;
  const sort = document.querySelector('#sort').value;
  let result = products
    .filter(p => p.name.toLowerCase().includes(q))
    .filter(p => cat === '' || p.category === cat);
  if (sort === 'low') result = [...result].sort((a, b) => a.price - b.price);
  if (sort === 'high') result = [...result].sort((a, b) => b.price - a.price);
  if (sort === 'rating') result = [...result].sort((a, b) => b.rating - a.rating);
  const avg = result.length ? result.reduce((s, p) => s + p.price, 0) / result.length : 0;
  document.querySelector('#summary').textContent = `${result.length} sweets · average ₹${Math.round(avg)}/kg`;
  document.querySelector('#list').innerHTML = result
    .map(p => `<li>${p.name} – ₹${p.price} ★${p.rating} ${p.stock === 0 ? '<b>(sold out)</b>' : ''}</li>`)
    .join('') || '<li>No sweets match</li>';
}
document.querySelectorAll('#q, #cat, #sort').forEach(el => el.addEventListener('input', render));
render();
</script>
▶  Type, choose a category, change the sort – filter + sort + reduce + map

🏅 आज के Job Skills

✔ map से arrays बदलना और forEach से काम✔ filter, find, some और every से चुनना✔ reduce से सारांश✔ Objects sort करना और methods को pipelines में chain करना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Marks [{name:"Aarav",m:72},{name:"Riya",m:91},{name:"Kabir",m:28},{name:"Sana",m:64}] से print करें: pass (≥ 33) students के नाम, class average और topper।
Solution देखें
JavaScript
const marks = [{ name: 'Aarav', m: 72 }, { name: 'Riya', m: 91 }, { name: 'Kabir', m: 28 }, { name: 'Sana', m: 64 }];
const passed = marks.filter(s => s.m >= 33).map(s => s.name);
const average = marks.reduce((sum, s) => sum + s.m, 0) / marks.length;
const topper = marks.reduce((best, s) => (s.m > best.m ? s : best));
console.log('Passed:', passed.join(', '));
console.log('Average:', average.toFixed(2));
console.log('Topper:', topper.name, topper.m);
Passed: Aarav, Riya, Sana Average: 63.75 Topper: Riya 91
Task 2: Expenses [{cat:"food",amt:250},{cat:"travel",amt:120},{cat:"food",amt:90}] को reduce से हर category के total में group करें।
Solution देखें
JavaScript
const expenses = [{ cat: 'food', amt: 250 }, { cat: 'travel', amt: 120 }, { cat: 'food', amt: 90 }];
const totals = expenses.reduce((acc, e) => {
  acc[e.cat] = (acc[e.cat] || 0) + e.amt;
  return acc;
}, {});
console.log(totals);
{ food: 340, travel: 120 }
Task 3: Day 4 की attendance report को loops की जगह map, filter और reduce से दोबारा लिखें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. [1,2,3].map(x => x * 2) लौटाता है…
नया बदला array।
2. कौन एक item लौटाता है?
पहला मेल।
3. [3,4].reduce((s, x) => s + x, 10) है…
10 + 3 + 4।
4. forEach लौटाता है…
Values वापस चाहिए तो map।
5. Products को price ज़्यादा से कम sort करें:
b - a = घटता क्रम।

Interview corner

💼 Interview Corner

map और forEach में फ़र्क?

map callback की return values का नया array लौटाता है और chain हो सकता है – data बदलने के लिए। forEach undefined लौटाता है और side effects के लिए है। दोनों ख़ुद array नहीं बदलते।

reduce से अपना map बनाइए।

const map = (arr, fn) => arr.reduce((acc, item, i) => { acc.push(fn(item, i, arr)); return acc; }, []); – reduce map और filter दोनों दर्शा सकता है क्योंकि वह कोई भी value बना सकता है।

सारांश

  • map बदलता है, filter चुनता है, find एक उठाता है, some/every जाँचते हैं।
  • reduce(fn, start) totals, गिनती और groups बनाता है।
  • Copy पर compare function से objects sort करें।
  • साफ़ data pipelines के लिए filter → sort → map chain।
➡️ आगे

Day 9: strings, numbers, पैसे और dates – रुपये format करना, paise सही round करना और delivery dates के साथ काम।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या ये methods for loops से धीमे हैं?
थोड़ा, पर सामान्य app data (सैकड़ों या हज़ारों items) में फ़र्क microseconds का है। पठनीयता जीतती है; मापने के बाद सिर्फ़ hot paths optimise करें।
Object.groupBy का क्या?
नए browsers और Node 21+ में Object.groupBy(items, fn) है। reduce हर जगह चलता है और विचार सिखाता है।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 9: Strings, Numbers, पैसे और Dates आपकी प्रगति: 8 / 30 (27%) · Lesson 9 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें