JavaScript Array Methods

Powerful Array Operations

Modern JavaScript has many built-in array methods that make working with arrays easier and more efficient.

These methods allow you to transform, filter, and process arrays without writing manual loops.

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

// map - Transform each element
const doubled = numbers.map(num => num * 2);
// [2, 4, 6, 8, 10]

// filter - Keep elements that pass test
const evens = numbers.filter(num => num % 2 === 0);
// [2, 4]

// find - Get first element that matches
const firstEven = numbers.find(num => num % 2 === 0);
// 2

// reduce - Reduce to single value
const sum = numbers.reduce((total, num) => total + num, 0);
// 15

// forEach - Loop through array
numbers.forEach(num => console.log(num));

// some - Check if any element passes test
const hasEven = numbers.some(num => num % 2 === 0);
// true

// every - Check if all elements pass test
const allPositive = numbers.every(num => num > 0);
// true

// sort - Sort array
const unsorted = [3, 1, 4, 1, 5, 9, 2, 6];
unsorted.sort((a, b) => a - b);  // Ascending
// [1, 1, 2, 3, 4, 5, 6, 9]

// Chaining methods
const result = numbers
  .filter(num => num > 2)
  .map(num => num * 2)
  .reduce((sum, num) => sum + num, 0);
// (3+4+5) * 2 = 24
  • map() - Transform each element
  • filter() - Keep matching elements
  • find() - Find first match
  • reduce() - Reduce to single value
  • forEach() - Loop through each
  • some() - Test if any match
  • every() - Test if all match
  • sort() - Sort array
  • Methods can be chained!

Try Array Methods

<div class="array-methods-demo">
  <h3>Student Grades</h3>
  <p>Grades: [85, 92, 78, 95, 88, 73, 90]</p>
  <button onclick="showStats()">Show Statistics</button>
  <button onclick="filterGrades()">Filter Grades</button>
  <div id="statsOutput"></div>
  
  <hr style="margin: 20px 0;">
  
  <h3>Product Prices</h3>
  <p>Prices: [$10, $25, $15, $30, $20]</p>
  <button onclick="applyDiscount()">Apply 20% Discount</button>
  <button onclick="findExpensive()">Find Expensive (>$20)</button>
  <div id="priceOutput"></div>
</div>

Note: Array methods are incredibly powerful! Master map, filter, and reduce - they're used everywhere in modern JavaScript.