map(), filter(), and reduce() in JavaScript:
๐น map()
- Purpose: Transforms each element and returns a new array.
- Does NOT mutate the original array.
- โ Used when you want to apply a function to each item.
const nums = [1, 2, 3];
const doubled = nums.map(num => num * 2);
console.log(doubled); // [2, 4, 6]
๐น filter()
- Purpose: Filters elements based on a condition.
- Returns a new array with elements that pass the test.
- โ Used when you want to keep some elements.
const nums = [1, 2, 3, 4];
const even = nums.filter(num => num % 2 === 0);
console.log(even); // [2, 4]
๐น reduce()
- Purpose: Reduces the array to a single value (number, object, string, etc.).
- Takes an accumulator and a current value.
- โ Used for summing, combining, counting, etc.
const nums = [1, 2, 3, 4];
const sum = nums.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10
๐ Summary:
| Method | Returns | Purpose |
|---|---|---|
map() |
New array | Transform items |
filter() |
Filtered array | Keep matching items |
reduce() |
Single value | Accumulate/combine values |