Arrays & Iteration — map, filter, reduce

৯০% for-loop-এর modern প্রতিস্থাপন

~40 min Intermediate 22 practice problems Live runner

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 (শব্দকোষ)

TermMeaningবাংলায়
mapReturns a new array of the same length with each element transformed.প্রতিটি element-কে রূপান্তর করে সম-দৈর্ঘ্য নতুন array।
filterKeeps elements for which the predicate returns true.Predicate true দিলে element রাখে।
reduceFolds an array into a single value via an accumulator.Array-কে একটি value-তে fold করে।
findReturns the first element matching the predicate, or undefined.প্রথম মিল-যাওয়া element ফেরত দেয়।
some / everyTrue if any / all elements match the predicate.Any/all element predicate পূরণ করছে কি?
ComparatorThe (a, b) => … function that sort uses.sort-কে দেওয়া তুলনা function।
flat / flatMapFlatten one (or all) levels of nested arrays.Nested array flatten করে।
toSorted / toReversedES2023 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

  1. Square every number in [1..5].
    ✨ Show Answer
    a1.js
    console.log([1,2,3,4,5].map(n => n * n));
  2. Get only words longer than 4 chars.
    ✨ Show Answer
    a2.js
    const w = ["cat", "horse", "hi", "banana"];
    console.log(w.filter(s => s.length > 4));
  3. Sum [10, 20, 30, 40] with reduce.
    ✨ Show Answer
    a3.js
    console.log([10,20,30,40].reduce((a,b) => a + b, 0));
  4. Find the first even number greater than 5.
    ✨ Show Answer
    a4.js
    console.log([3,7,8,12,5].find(n => n > 5 && n % 2 === 0));
  5. Sort numbers numerically (not alphabetically).
    ✨ Show Answer
    a5.js
    console.log([10,2,33,4].toSorted((a,b) => a - b));
  6. Sort users by age descending.
    ✨ Show Answer
    a6.js
    const u = [{n:"a",age:22}, {n:"b",age:35}, {n:"c",age:28}];
    console.log(u.toSorted((a,b) => b.age - a.age));
  7. Flatten [1,[2,[3,[4]]]] completely.
    ✨ Show Answer
    a7.js
    console.log([1,[2,[3,[4]]]].flat(Infinity));
  8. Count word frequencies in a sentence using reduce.
    ✨ Show Answer
    a8.js
    const 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);
  9. Get unique values from [1,2,2,3,3,3,4].
    ✨ Show Answer
    a9.js
    console.log([...new Set([1,2,2,3,3,3,4])]);
  10. Build a frequency map and the top-3 words.
    ✨ Show Answer
    a10.js
    const 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);
  11. Use flatMap to split sentences into words.
    ✨ Show Answer
    a11.js
    const s = ["hello world", "good morning"];
    console.log(s.flatMap(x => x.split(" ")));
  12. Compute average mark of a class.
    ✨ Show Answer
    a12.js
    const marks = [82, 71, 95, 66, 88];
    console.log(marks.reduce((a,b) => a + b, 0) / marks.length);
  13. Use some to check if any number is negative.
    ✨ Show Answer
    a13.js
    console.log([3, -1, 5].some(n => n < 0));
  14. Use every to verify all marks are passing (≥40).
    ✨ Show Answer
    a14.js
    console.log([42,55,76].every(n => n >= 40));
  15. Build [1, 2, ..., 100] using Array.from.
    ✨ Show Answer
    a15.js
    const arr = Array.from({ length: 100 }, (_, i) => i + 1);
    console.log(arr.length, arr[0], arr.at(-1));
  16. Group people by city using reduce.
    ✨ Show Answer
    a16.js
    const 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), {}));
  17. Chain filter→map→reduce in one pipeline (sum of doubled odd).
    ✨ Show Answer
    a17.js
    console.log([1,2,3,4,5]
        .filter(n => n % 2)
        .map(n => n * 2)
        .reduce((a, b) => a + b, 0));
  18. Reverse without mutating using toReversed.
    ✨ Show Answer
    a18.js
    const a = [1,2,3];
    console.log(a.toReversed(), a);
  19. Implement a tiny groupBy helper.
    ✨ Show Answer
    a19.js
    const 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"));
  20. Find indices of all occurrences of a value.
    ✨ Show Answer
    a20.js
    const a = [1,2,3,2,4,2];
    const idx = a.map((v, i) => v === 2 ? i : -1).filter(i => i >= 0);
    console.log(idx);
  21. Why is arr.sort() alphabetical by default?
    ✨ Show Answer

    Answer: Without a comparator, sort coerces 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.

  22. Use at() to get the last element of an array.
    ✨ Show Answer
    a22.js
    const 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) আধুনিক কোডে অগ্রাধিকার।

Next Module → Destructuring, Spread & Rest।