Arrays & Iteration — map, filter, reduce
৯০% for-loop-এর modern প্রতিস্থাপন
1. Creating Arrays
create.js
const a = [1, 2, 3]; // literal
const b = Array.of(1, 2, 3); // equivalent
const c = Array.from("abc"); // ["a","b","c"]
const d = Array.from({ length: 5 }, (_, i) => i * i);
// [0, 1, 4, 9, 16]
const e = new Array(3).fill(0); // [0,0,0]
console.log(a, b, c, d, e);
2. Mutating Methods (Be Careful)
mutate.js
const a = [1, 2, 3];
a.push(4); console.log(a); // [1,2,3,4]
a.pop(); console.log(a); // [1,2,3]
a.unshift(0); console.log(a); // [0,1,2,3]
a.shift(); console.log(a); // [1,2,3]
a.splice(1, 1, "x"); console.log(a); // [1,"x",3] in-place
a.reverse(); console.log(a); // in-place
a.sort(); console.log(a);
// Non-mutating cousins (ES2023): toSorted, toReversed, toSpliced, with
const sorted = [3, 1, 2].toSorted();
console.log(sorted);
3. map, filter, reduce
mfr.js
const nums = [1, 2, 3, 4, 5];
// map — transform each element
console.log(nums.map(n => n * n)); // [1,4,9,16,25]
// filter — keep matching
console.log(nums.filter(n => n % 2)); // [1,3,5]
// reduce — fold to a single value
console.log(nums.reduce((a, b) => a + b, 0)); // 15
// Chain — all in one expression
const sumOfSquaresOfEvens = nums
.filter(n => n % 2 === 0)
.map(n => n * n)
.reduce((a, b) => a + b, 0);
console.log(sumOfSquaresOfEvens); // 4 + 16 = 20
তিনটি method মনে রাখুন —
map রূপান্তর করে, filter বেছে নেয়, reduce একটি value-তে fold করে। এই তিনটি দিয়ে for-loop-এর প্রায় সব কাজ হয়।4. find, some, every, includes
search.js
const users = [
{ name: "Arif", age: 22 },
{ name: "Karim", age: 35 },
{ name: "Nusrat", age: 28 },
];
console.log(users.find(u => u.age > 30)); // Karim
console.log(users.findIndex(u => u.age > 30)); // 1
console.log(users.some(u => u.age > 30)); // true
console.log(users.every(u => u.age > 18)); // true
console.log([1,2,3].includes(2)); // true
5. sort — The Comparator Trap
Default sort compares as strings. Always pass a comparator for numbers.
sort.js
console.log([10, 2, 33, 4].toSorted()); // [10,2,33,4] sorted as strings!
console.log([10, 2, 33, 4].toSorted((a, b) => a - b));
// [2, 4, 10, 33]
const users = [{ name:"Arif", age:22}, { name:"Karim", age:35}];
console.log(users.toSorted((a, b) => b.age - a.age)); // desc by age
6. flat, flatMap
flat.js
console.log([1, [2, [3, [4]]]].flat()); // [1,2,[3,[4]]]
console.log([1, [2, [3, [4]]]].flat(Infinity));// [1,2,3,4]
// flatMap = map then flat(1) — useful
const sentences = ["hello world", "how are you"];
console.log(sentences.flatMap(s => s.split(" ")));
// ["hello","world","how","are","you"]
7. Destructuring & Spread
destruct.js
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest);
// Clone
const a = [1, 2, 3];
const copy = [...a];
copy.push(99);
console.log(a, copy);
// Concat
console.log([...[1,2], ...[3,4]]);
8. Glossary (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
map | Returns a new array of the same length with each element transformed. | প্রতিটি element-কে রূপান্তর করে সম-দৈর্ঘ্য নতুন array। |
filter | Keeps elements for which the predicate returns true. | Predicate true দিলে element রাখে। |
reduce | Folds an array into a single value via an accumulator. | Array-কে একটি value-তে fold করে। |
find | Returns the first element matching the predicate, or undefined. | প্রথম মিল-যাওয়া element ফেরত দেয়। |
some / every | True if any / all elements match the predicate. | Any/all element predicate পূরণ করছে কি? |
| Comparator | The (a, b) => … function that sort uses. | sort-কে দেওয়া তুলনা function। |
flat / flatMap | Flatten one (or all) levels of nested arrays. | Nested array flatten করে। |
toSorted / toReversed | ES2023 non-mutating cousins of sort/reverse. | Mutate না করে নতুন array দেয়। |
at() | Negative-index access: arr.at(-1) = last. | Negative index allow করে — arr.at(-1) শেষ item। |
মনে রাখার নিয়ম: তিনটি method মুখস্থ —
map রূপান্তর, filter বাছাই, reduce fold। এই তিনটি দিয়ে for-loop-এর প্রায় সব কাজ চলে। Numeric sort-এ comparator (a, b) => a - b ভুলবেন না — default sort string-হিসেবে compare করে। toSorted/toReversed non-mutating, original array নিরাপদ থাকে।
9. Practice Problems
- Square every number in [1..5].
✨ Show Answer
a1.jsconsole.log([1,2,3,4,5].map(n => n * n)); - Get only words longer than 4 chars.
✨ Show Answer
a2.jsconst w = ["cat", "horse", "hi", "banana"]; console.log(w.filter(s => s.length > 4)); - Sum [10, 20, 30, 40] with reduce.
✨ Show Answer
a3.jsconsole.log([10,20,30,40].reduce((a,b) => a + b, 0)); - Find the first even number greater than 5.
✨ Show Answer
a4.jsconsole.log([3,7,8,12,5].find(n => n > 5 && n % 2 === 0)); - Sort numbers numerically (not alphabetically).
✨ Show Answer
a5.jsconsole.log([10,2,33,4].toSorted((a,b) => a - b)); - Sort users by age descending.
✨ Show Answer
a6.jsconst u = [{n:"a",age:22}, {n:"b",age:35}, {n:"c",age:28}]; console.log(u.toSorted((a,b) => b.age - a.age)); - Flatten
[1,[2,[3,[4]]]]completely.✨ Show Answer
a7.jsconsole.log([1,[2,[3,[4]]]].flat(Infinity)); - Count word frequencies in a sentence using reduce.
✨ Show Answer
a8.jsconst txt = "the cat sat on the mat the"; const freq = txt.split(" ").reduce((acc, w) => { acc[w] = (acc[w] || 0) + 1; return acc; }, {}); console.log(freq); - Get unique values from
[1,2,2,3,3,3,4].✨ Show Answer
a9.jsconsole.log([...new Set([1,2,2,3,3,3,4])]); - Build a frequency map and the top-3 words.
✨ Show Answer
a10.jsconst txt = "the cat sat on the mat the cat sat"; const top = Object.entries( txt.split(" ").reduce((a, w) => (a[w] = (a[w] || 0) + 1, a), {}) ).toSorted((a, b) => b[1] - a[1]).slice(0, 3); console.log(top); - Use
flatMapto split sentences into words.✨ Show Answer
a11.jsconst s = ["hello world", "good morning"]; console.log(s.flatMap(x => x.split(" "))); - Compute average mark of a class.
✨ Show Answer
a12.jsconst marks = [82, 71, 95, 66, 88]; console.log(marks.reduce((a,b) => a + b, 0) / marks.length); - Use
someto check if any number is negative.✨ Show Answer
a13.jsconsole.log([3, -1, 5].some(n => n < 0)); - Use
everyto verify all marks are passing (≥40).✨ Show Answer
a14.jsconsole.log([42,55,76].every(n => n >= 40)); - Build [1, 2, ..., 100] using
Array.from.✨ Show Answer
a15.jsconst arr = Array.from({ length: 100 }, (_, i) => i + 1); console.log(arr.length, arr[0], arr.at(-1)); - Group people by city using reduce.
✨ Show Answer
a16.jsconst p = [{n:"a",c:"D"},{n:"b",c:"C"},{n:"x",c:"D"}]; console.log(p.reduce((a, x) => ((a[x.c] ??= []).push(x.n), a), {})); - Chain filter→map→reduce in one pipeline (sum of doubled odd).
✨ Show Answer
a17.jsconsole.log([1,2,3,4,5] .filter(n => n % 2) .map(n => n * 2) .reduce((a, b) => a + b, 0)); - Reverse without mutating using
toReversed.✨ Show Answer
a18.jsconst a = [1,2,3]; console.log(a.toReversed(), a); - Implement a tiny groupBy helper.
✨ Show Answer
a19.jsconst groupBy = (arr, fn) => arr.reduce( (acc, x) => ((acc[fn(x)] ??= []).push(x), acc), {}); console.log(groupBy([1,2,3,4,5], n => n % 2 ? "odd" : "even")); - Find indices of all occurrences of a value.
✨ Show Answer
a20.jsconst a = [1,2,3,2,4,2]; const idx = a.map((v, i) => v === 2 ? i : -1).filter(i => i >= 0); console.log(idx); - Why is
arr.sort()alphabetical by default?✨ Show Answer
Answer: Without a comparator,
sortcoerces every element to its string form and compares lexicographically —"10"comes before"2"because"1" < "2". To sort numerically, always pass(a, b) => a - b. - Use
at()to get the last element of an array.✨ Show Answer
a22.jsconst a = [10, 20, 30]; console.log(a.at(-1)); // 30
Summary — Module 14
Master map, filter, reduce and most for-loops disappear. Use the new non-mutating cousins (toSorted, toReversed) to keep code declarative. Always supply a comparator for numeric sorts. flat/flatMap, find/findIndex, some/every, and at() round out the toolkit.
map/filter/reduce — তিনটি মূল ভিত্তি। numerical sort-এ comparator দিতে ভুলবেন না। non-mutating নতুন method (
toSorted) আধুনিক কোডে অগ্রাধিকার।