दिन 6: Arrays और उनके रोज़ के Methods
✅ आज आप सीखेंगे
- Arrays बनाना और index से items पढ़ना
- जोड़ना और हटाना: push, pop, unshift, shift, splice
- ढूँढना: indexOf, includes, at()
- Copy और जोड़ना: slice, spread, concat, join
- Numbers को सही sort करना और mutation की गड़बड़ियाँ
🏢 असली दुनिया में
Cart एक list है। आज के orders, class के marks, menu की मिठाइयाँ और app की notifications भी। Arrays JavaScript का सबसे ज़्यादा इस्तेमाल होने वाला data structure हैं। School app का असली bug: marks [9, 80, 100, 45] को “सबसे कम से ज़्यादा” sort करने पर [100, 45, 80, 9] मिला। आज आप ठीक-ठीक देखेंगे क्यों।
Arrays बनाना और पढ़ना
const sweets = ['Kaju Katli', 'Ghewar', 'Rasmalai', 'Ladoo']; console.log(sweets[0]); // first item – index starts at 0 console.log(sweets[sweets.length - 1]); // last item console.log(sweets.at(-1)); // modern way to read from the end console.log(sweets.length); console.log(sweets[10]); // undefined – no error! sweets[1] = 'Malai Ghewar'; // change an item console.log(sweets); const mixed = ['Riya', 16, true, ['Maths', 'Science']]; // any types, even arrays console.log(mixed[3][1]);
जोड़ना और हटाना
const cart = ['Ladoo'];
cart.push('Kaju Katli', 'Ghewar'); // add to the END
cart.unshift('Gift Box'); // add to the START
console.log(cart);
const last = cart.pop(); // remove from the END
const first = cart.shift(); // remove from the START
console.log(last, first, cart);
// splice(start, deleteCount, ...itemsToInsert) – change the middle
const menu = ['Kaju', 'Ghewar', 'Rasmalai', 'Ladoo'];
const removed = menu.splice(1, 2, 'Kalakand'); // remove 2 from index 1, insert 1
console.log(removed, menu);| Method | क्या करता है | Array बदलता है? | लौटाता है |
|---|---|---|---|
| push(x) | अंत में जोड़ो | हाँ | नई length |
| pop() | आख़िरी हटाओ | हाँ | हटाया item |
| unshift(x) | शुरू में जोड़ो | हाँ | नई length |
| shift() | पहला हटाओ | हाँ | हटाया item |
| splice(i, n, …) | बीच में हटाओ/डालो | हाँ | हटाए items का array |
| slice(a, b) | a से b-1 तक copy | नहीं ⭐ | नया array |
| concat / [...a, ...b] | Arrays जोड़ना | नहीं | नया array |
| join(sep) | Array → string | नहीं | String |
sPlice में “P” है “Permanent बदलाव” का: यह original बदलता है। slice सिर्फ़ copy करता है। React और आधुनिक apps में non-mutating methods पसंद करें ताकि पुराना data सुरक्षित रहे।
Array में खोजना
const pinCodes = [302001, 302003, 302004, 302012];
const customerPin = 302003;
console.log(pinCodes.includes(customerPin) ? 'We deliver here ✅' : 'Not in delivery area');
console.log(pinCodes.indexOf(302004)); // position, or -1 if missing
console.log(pinCodes.indexOf(110001));
const tags = ['veg', 'sugar-free', 'gift'];
console.log(tags.join(' · '));
console.log('kaju,ghewar,ladoo'.split(',')); // string → arrayCopies, spread और reference का जाल
const original = ['Kaju', 'Ghewar'];
const sameBox = original; // NOT a copy – both names point to one array
sameBox.push('Ladoo');
console.log(original); // changed too!
const realCopy = [...original]; // spread = new array
realCopy.push('Rasmalai');
console.log(original, realCopy);
const festive = [...original, 'Gift Box', ...['Soan Papdi']];
console.log(festive);Sorting – number वाला bug
const marks = [9, 80, 100, 45]; console.log([...marks].sort()); // ❌ sorts as TEXT: "100" < "45" < "80" < "9" console.log([...marks].sort((a, b) => a - b)); // ✅ ascending numbers console.log([...marks].sort((a, b) => b - a)); // ✅ descending const names = ['riya', 'Aarav', 'kabir']; console.log([...names].sort((a, b) => a.localeCompare(b))); // case-insensitive A–Z console.log(marks.toSorted ? 'toSorted() also exists and never mutates' : '');
असली task: shopping list
<input id="item" placeholder="e.g. 1 kg Ghewar" aria-label="Item">
<button id="add">Add</button> <button id="undo">Remove last</button>
<p id="count"></p>
<ol id="list"></ol>
<script>
const list = [];
function render() {
document.querySelector('#list').innerHTML = list.map(x => `<li>${x}</li>`).join('');
document.querySelector('#count').textContent = `${list.length} item(s)`;
}
document.querySelector('#add').addEventListener('click', () => {
const box = document.querySelector('#item');
const text = box.value.trim();
if (text === '') return;
if (list.includes(text)) { alert('Already in the list'); return; }
list.push(text);
box.value = '';
render();
});
document.querySelector('#undo').addEventListener('click', () => { list.pop(); render(); });
render();
</script>Data array में रखें, array बदलें, फिर एक render() function बुलाएँ जो data से HTML दोबारा बनाए। यह “data → UI” विचार ठीक वैसा है जैसे React काम करता है – इस course के हर project में आप इसे इस्तेमाल करेंगे।
🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
Solution देखें
const queue = ['A101', 'A102', 'A103'];
const served = queue.shift();
queue.push('A104');
console.log('Served:', served);
console.log('Next:', queue[0], '| waiting:', queue.length, queue.join(', '));Solution देखें
const prices = [380, 900, 650, 500, 720]; const top3 = [...prices].sort((a, b) => b - a).slice(0, 3); console.log(top3, prices);
Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Array कैसे copy करें, और shallow copy क्या है?
[...arr], arr.slice() या Array.from(arr) नया array बनाते हैं, पर अंदर के nested objects/arrays अब भी साझा references हैं (shallow)। Deep copy के लिए structuredClone(arr)।
[1, 10, 2].sort() [1, 10, 2] क्यों लौटाता है?
Compare function के बिना sort items को strings बनाकर UTF-16 क्रम से तुलना करता है, इसलिए "10" "2" से पहले आता है। Numbers के लिए (a, b) => a - b दें।
सारांश
- Index 0 से; length; आख़िरी item के लिए at(-1)।
- push/pop/shift/unshift/splice array बदलते हैं; slice/spread/concat copy करते हैं।
- खोजने व बदलने के लिए includes, indexOf, join, split।
- Numbers (a, b) => a - b से sort; data → render() → UI रखें।
Day 7: objects – असली चीज़ें (product, order, student) properties, methods, destructuring और JSON से।
