Array Methods

📚 Lesson 10 of 22  •  ⏱ 13 min read  •  Intermediate

map — Transform Each Element

JavaScript
const prices = [100, 200, 300];

// Apply 18% GST to all prices
const withGST = prices.map(p => p * 1.18);
// [118, 236, 354]

const users = [{ name: "Ravi" }, { name: "Priya" }];
const names = users.map(u => u.name);
// ["Ravi", "Priya"]

// map always returns a NEW array of the same length
// Original array is NOT modified

filter — Keep Matching Elements

JavaScript
const scores = [45, 72, 38, 91, 60];

const passed = scores.filter(s => s >= 50);
// [72, 91, 60]

const products = [
  { name: "Laptop", inStock: true },
  { name: "Phone",  inStock: false },
  { name: "Tablet", inStock: true }
];
const available = products.filter(p => p.inStock);
// [{name:"Laptop"...}, {name:"Tablet"...}]

reduce — Accumulate to One Value

JavaScript
const cart = [
  { item: "Book",   price: 250 },
  { item: "Pen",    price: 30 },
  { item: "Bag",    price: 800 }
];

// Sum of prices — reduce(callback, initialValue)
const total = cart.reduce((sum, item) => sum + item.price, 0);
// 1080

// Group by category
const grouped = items.reduce((acc, item) => {
  acc[item.category] = acc[item.category] || [];
  acc[item.category].push(item);
  return acc;
}, {});

find, findIndex, some, every

JavaScript
const users = [
  { id: 1, name: "Ravi",  admin: false },
  { id: 2, name: "Priya", admin: true },
  { id: 3, name: "Kumar", admin: false }
];

// find — first match or undefined
users.find(u => u.admin)         // {id:2, name:"Priya"...}
users.findIndex(u => u.id === 3) // 2

// some — true if ANY match
users.some(u => u.admin)   // true

// every — true if ALL match
users.every(u => u.admin)  // false

sort

JavaScript
// Default sort converts to strings — wrong for numbers!
[10, 9, 100].sort()          // [10, 100, 9] — wrong

// Numeric sort with comparator
[10, 9, 100].sort((a, b) => a - b)  // [9, 10, 100] — ascending
[10, 9, 100].sort((a, b) => b - a)  // [100, 10, 9] — descending

// Sort by object property
users.sort((a, b) => a.name.localeCompare(b.name));

// sort mutates the array — clone first to keep original
const sorted = [...users].sort((a, b) => a.name.localeCompare(b.name));

Chaining Methods

JavaScript
const students = [
  { name: "Ravi",  score: 82 },
  { name: "Priya", score: 45 },
  { name: "Kumar", score: 91 },
  { name: "Sita",  score: 67 }
];

// Get names of students who passed, sorted alphabetically
const result = students
  .filter(s => s.score >= 50)
  .sort((a, b) => a.score - b.score)
  .map(s => `${s.name}: ${s.score}`);

// ["Sita: 67", "Ravi: 82", "Kumar: 91"]