Array Methods

Transform, search, and iterate through arrays with built-in methods.

forEach

Execute a function for each element. Returns nothing.

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

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

// forEach returns undefined — use for side effects only

map

Transform every element. Returns a new array.

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

const doubled = nums.map(n => n * 2);
// [2, 4, 6, 8, 10]

const strings = nums.map(n => `Item ${n}`);
// ["Item 1", "Item 2", ...]

// Original is unchanged:
console.log(nums); // [1, 2, 3, 4, 5]

.map(n => n * 2)

1
2
3
4
5

filter

Keep only elements that pass a test. Returns a new array.

const nums = [1, 2, 3, 4, 5, 6, 7, 8];

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

const long = ["hi", "hello", "hey"].filter(s => s.length > 2);
// ["hello", "hey"]

// Remove falsy values:
const clean = [0, 1, "", "hi", null, true].filter(Boolean);
// [1, "hi", true]

.filter(n => n % 2 === 0)

12345678

find & includes

Search for elements in an array.

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Carol", age: 28 },
];

// find — returns first match (or undefined):
users.find(u => u.age > 26);
// { name: "Bob", age: 30 }

// findIndex — returns index of first match:
users.findIndex(u => u.name === "Carol"); // 2

// includes — check if value exists (primitives):
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(5); // false

// some — does ANY element pass the test?
users.some(u => u.age >= 30); // true

// every — do ALL elements pass?
users.every(u => u.age >= 18); // true

reduce

Accumulate all elements into a single value.

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

const sum = nums.reduce((acc, curr) => {
  return acc + curr;
}, 0);
// sum = 15

reduce takes a callback with an accumulator and current value, plus an initial value (0). It processes each element, building up a result.

💡 reduce(callback, initialValue)
1 / 3

Method Chaining

Combine methods for powerful data transformations.

const products = [
  { name: "Laptop", price: 999, inStock: true },
  { name: "Phone", price: 699, inStock: false },
  { name: "Tablet", price: 499, inStock: true },
  { name: "Watch", price: 299, inStock: true },
];

// Chain: filter → map → sort
const affordable = products
  .filter(p => p.inStock)        // only in-stock
  .filter(p => p.price < 600)    // under $600
  .map(p => p.name)              // get names
  .sort();                       // alphabetical

// ["Tablet", "Watch"]

💡 Chaining works because filter and map return new arrays. Methods like forEach return undefined and can't be chained.

FAQ

Common questions about array methods.