दिन 8: map, filter, reduce, find और sort
✅ आज आप सीखेंगे
- 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
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));filter, find, some, every
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));| Method | लौटाता है | कब |
|---|---|---|
| map(fn) | नया array, वही length | बदलना: prices → labels, data → HTML |
| filter(fn) | नया array, 0..n items | मेल खाते items रखना: stock, category |
| find(fn) | पहला मेल या undefined | id से एक product ढूँढना |
| findIndex(fn) | Index या -1 | Item को उसी जगह बदलना/हटाना |
| 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 से एक
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);दूसरे argument के बिना reduce पहले item को start मानता है, जो ख़ाली array पर crash करता है (“Reduce of empty array with no initial value”) और items objects हों तो गड़बड़ करता है। Sums के लिए 0, grouping के लिए {}, lists के लिए []।
Objects के arrays sort करना
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]);Chaining: data pipeline
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'));असली task: live product filter
<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>🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
Solution देखें
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);Solution देखें
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);Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
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 के साथ काम।
