JavaScript Array Methods

JavaScript arrays come with a powerful set of built-in methods that transform, search, and process data without the need for manual loops. These functional methods are essential tools in modern JavaScript development.

map() — Transform Every Element

map() creates a new array by applying a function to every element of the original array. The original array is never modified.

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

let doubled = numbers.map(num => num * 2);
console.log(doubled);   // [2, 4, 6, 8, 10]
console.log(numbers);   // [1, 2, 3, 4, 5] — unchanged

Practical map() Examples

// Extract names from a list of objects
let students = [
  { name: "Arun", score: 85 },
  { name: "Priya", score: 92 },
  { name: "Rahul", score: 78 }
];

let names = students.map(student => student.name);
console.log(names);  // ["Arun", "Priya", "Rahul"]

// Convert Celsius to Fahrenheit
let celsius = [0, 20, 37, 100];
let fahrenheit = celsius.map(c => (c * 9/5) + 32);
console.log(fahrenheit);  // [32, 68, 98.6, 212]

filter() — Select Elements That Meet a Condition

filter() creates a new array with only the elements that pass a given test (return true).

let scores = [40, 75, 55, 90, 30, 80];

let passed = scores.filter(score => score >= 50);
console.log(passed);  // [75, 55, 90, 80]

Practical filter() Examples

// Filter products by price
let products = [
  { name: "Phone", price: 15000 },
  { name: "Charger", price: 800 },
  { name: "Laptop", price: 55000 },
  { name: "Earbuds", price: 1200 }
];

let affordable = products.filter(p => p.price <= 1500);
console.log(affordable);
// [{ name: "Charger", price: 800 }, { name: "Earbuds", price: 1200 }]

// Remove falsy values from an array
let data = [0, "hello", "", null, 42, undefined, "world"];
let clean = data.filter(Boolean);
console.log(clean);  // ["hello", 42, "world"]

reduce() — Combine All Elements into One Value

reduce() processes every element in an array and accumulates a single result. It takes a callback and an optional initial value.

let numbers = [10, 20, 30, 40];

let total = numbers.reduce((accumulator, current) => accumulator + current, 0);
console.log(total);  // 100

The accumulator holds the running result. The current value is the element being processed in each iteration.

Practical reduce() Examples

// Calculate total price of cart items
let cart = [
  { item: "Notebook", price: 50 },
  { item: "Pen", price: 20 },
  { item: "Ruler", price: 30 }
];

let totalCost = cart.reduce((sum, product) => sum + product.price, 0);
console.log("Total:", totalCost);  // Total: 100

// Find the maximum number
let nums = [5, 12, 3, 19, 7];
let max = nums.reduce((highest, current) => current > highest ? current : highest);
console.log("Max:", max);  // Max: 19

// Count occurrences of items
let fruits = ["apple", "banana", "apple", "mango", "banana", "apple"];
let count = fruits.reduce((tally, fruit) => {
  tally[fruit] = (tally[fruit] || 0) + 1;
  return tally;
}, {});

console.log(count);
// { apple: 3, banana: 2, mango: 1 }

find() — Get First Matching Element

find() returns the first element that passes a test. If nothing is found, it returns undefined.

let users = [
  { id: 1, name: "Kavitha" },
  { id: 2, name: "Suresh" },
  { id: 3, name: "Divya" }
];

let user = users.find(u => u.id === 2);
console.log(user);  // { id: 2, name: "Suresh" }

findIndex() — Get Position of First Matching Element

findIndex() works like find() but returns the index (position) instead of the element itself. Returns -1 if not found.

let scores = [55, 90, 73, 88];

let index = scores.findIndex(s => s > 85);
console.log(index);  // 1 (index of 90)

some() — Check if Any Element Passes

some() returns true if at least one element passes the test.

let scores = [40, 55, 35, 70, 20];

let hasPassingScore = scores.some(score => score >= 50);
console.log(hasPassingScore);  // true (55 and 70 pass)

every() — Check if All Elements Pass

every() returns true only if all elements pass the test.

let temperatures = [36.5, 37.1, 36.8, 37.0];

let allNormal = temperatures.every(temp => temp < 38);
console.log(allNormal);  // true

flat() and flatMap()

flat() — Flatten Nested Arrays

let nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());    // [1, 2, 3, 4, [5, 6]] (one level deep)
console.log(nested.flat(2));   // [1, 2, 3, 4, 5, 6]  (two levels deep)
console.log(nested.flat(Infinity));  // Fully flatten any depth

flatMap() — Map then Flatten

let sentences = ["Hello World", "JavaScript Rocks"];

let words = sentences.flatMap(s => s.split(" "));
console.log(words);  // ["Hello", "World", "JavaScript", "Rocks"]

forEach() — Iterate Without Returning

forEach() executes a function on each element. Unlike map(), it does not return a new array. Use it for side effects like logging or DOM updates.

let items = ["Pen", "Notebook", "Eraser"];

items.forEach((item, index) => {
  console.log(`${index + 1}. ${item}`);
});
// 1. Pen
// 2. Notebook
// 3. Eraser

Chaining Array Methods

Array methods can be chained together for powerful data transformations.

let employees = [
  { name: "Reena", dept: "HR", salary: 40000 },
  { name: "Mohan", dept: "Tech", salary: 75000 },
  { name: "Sana", dept: "Tech", salary: 90000 },
  { name: "Tarun", dept: "HR", salary: 35000 }
];

// Get names of Tech employees earning more than 70000, sorted A-Z
let result = employees
  .filter(e => e.dept === "Tech" && e.salary > 70000)
  .map(e => e.name)
  .sort();

console.log(result);  // ["Mohan", "Sana"]

Method Comparison Table

MethodReturnsUse For
map()New array (same length)Transforming each element
filter()New array (shorter)Selecting elements by condition
reduce()Single valueCombining all elements
find()First matching elementFinding one element
findIndex()Index of first matchFinding element's position
some()BooleanChecking if any match
every()BooleanChecking if all match
forEach()undefinedSide effects on each element
flat()New flat arrayFlattening nested arrays
flatMap()New flat arrayMap and flatten in one step

Key Points to Remember

  • map() transforms each element and returns a new array of the same length
  • filter() selects elements that pass a condition and returns a shorter array
  • reduce() combines all elements into a single result using an accumulator
  • find() returns the first matching element; findIndex() returns its position
  • some() returns true if at least one element passes; every() requires all to pass
  • None of these methods (except sort() and reverse()) modify the original array
  • Array methods can be chained to create powerful data pipelines

Leave a Comment

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