JavaScript Lesson 13: Array Methods

⚡ JavaScript CourseLesson 13 of 20 · 65% complete

Array methods like map, filter, and reduce are fundamental to modern JavaScript. They let you transform data without writing manual loops — your code becomes shorter and clearer.

forEach — Loop Without Return

const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit, index) => {
  console.log(`${index + 1}. ${fruit}`);
});
// 1. apple
// 2. banana
// 3. cherry

map — Transform Every Element

const numbers = [1, 2, 3, 4, 5];

// Create a new array (original unchanged)
const doubled = numbers.map(n => n * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

const users = [{ name: "Alice" }, { name: "Bob" }];
const names = users.map(u => u.name);
console.log(names);  // ["Alice", "Bob"]

filter — Keep Only Matching Items

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);  // [2, 4, 6, 8, 10]

const products = [
  { name: "Book", price: 15 },
  { name: "Laptop", price: 999 },
  { name: "Pen", price: 3 }
];
const affordable = products.filter(p => p.price < 100);
console.log(affordable);  // [Book, Pen]

reduce — Combine to Single Value

const numbers = [1, 2, 3, 4, 5];

// Sum all numbers
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum);  // 15

// Find maximum
const max = numbers.reduce((max, n) => n > max ? n : max, -Infinity);
console.log(max);  // 5

// Count occurrences
const words = ["yes", "no", "yes", "yes", "no"];
const count = words.reduce((acc, word) => {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {});
console.log(count);  // { yes: 3, no: 2 }

find, some, every, sort

const nums = [5, 3, 8, 1, 9, 2];

console.log(nums.find(n => n > 7));    // 8 (first match)
console.log(nums.some(n => n > 10));   // false
console.log(nums.every(n => n > 0));   // true
console.log([...nums].sort((a, b) => a - b));  // [1,2,3,5,8,9]

🏋️ Practice Task

You have an array of products: [{name, price, category}]. Write code using map/filter/reduce to: (1) get all product names, (2) find products under $50, (3) calculate the total value of all products, (4) sort by price ascending.

💡 Hint: Chain methods: products.filter(…).map(…). For sort: products.sort((a,b) => a.price – b.price)

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *