JavaScript Array Methods — The Complete Guide

Published: June 2025 • 18 min read • Category: JavaScript

Arrays are one of JavaScript's most fundamental data structures, and knowing which array methods to use — and when — can make your code cleaner, faster, and more expressive. This guide covers every essential JavaScript array method with practical, real-world examples you can use immediately.

📋 Quick Navigation

  1. Iteration: forEach, map, filter
  2. Reduction: reduce, reduceRight
  3. Searching: find, findIndex, indexOf, includes
  4. Transformation: flat, flatMap, join, reverse
  5. Sorting & Ordering: sort, toSorted, toReversed
  6. Mutation: push, pop, shift, unshift, splice
  7. New Immutable Methods: toSpliced, with
  8. Array.from, Array.of, and Set operations
  9. Common Patterns & Best Practices
  10. Performance Tips

1. Iteration Methods

Iteration methods let you loop through array elements and apply transformations, filters, or execute side effects.

Array.prototype.map() Popular

map() creates a new array by applying a function to every element. It doesn't modify the original array.

const prices = [19.99, 5.99, 12.50, 8.75];
const pricesWithTax = prices.map(price => (price * 1.08).toFixed(2));

console.log(pricesWithTax);
// ["21.59", "6.47", "13.50", "9.45"]

const users = [
  { name: 'Alice', age: 28 },
  { name: 'Bob', age: 34 },
  { name: 'Charlie', age: 22 }
];
const names = users.map(user => user.name);
// ["Alice", "Bob", "Charlie"]

Array.prototype.filter() Popular

filter() creates a new array containing only elements that pass a test condition.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4, 6, 8, 10]

const products = [
  { name: 'Laptop', price: 999, inStock: true },
  { name: 'Phone', price: 699, inStock: false },
  { name: 'Tablet', price: 349, inStock: true },
  { name: 'Watch', price: 199, inStock: false }
];
const available = products.filter(p => p.inStock && p.price < 500);
// [{ name: 'Tablet', price: 349, inStock: true }]

Array.prototype.forEach()

forEach() executes a function for each element. Unlike map(), it returns undefined and is designed for side effects.

const emails = ['alice@example.com', 'bob@example.com'];
emails.forEach(email => {
  console.log(`Sending to ${email}...`);
});
📌 Note: Prefer map() or filter() over forEach() when you need a return value. Use forEach() for side effects like logging or DOM manipulation.

Array.prototype.every() & some()

every() returns true if all elements pass a test. some() returns true if at least one element passes.

const scores = [85, 92, 78, 95, 88];
const allPassing = scores.every(s => s >= 70);  // true
const anyPerfect = scores.some(s => s === 100); // false

const products = [{ price: 10 }, { price: 25 }, { price: 5 }];
const allAffordable = products.every(p => p.price < 50); // true

2. Reduction: reduce()

reduce() is one of the most powerful and versatile array methods. It "reduces" an array to a single value by applying a function to each element, accumulating the result.

Basic Sum

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
// 15

Group Objects by Property

const orders = [
  { product: 'Laptop', category: 'Electronics' },
  { product: 'Shirt', category: 'Clothing' },
  { product: 'Phone', category: 'Electronics' },
  { product: 'Pants', category: 'Clothing' },
  { product: 'Headphones', category: 'Electronics' }
];

const grouped = orders.reduce((acc, order) => {
  (acc[order.category] ??= []).push(order.product);
  return acc;
}, {});
// { Electronics: ["Laptop", "Phone", "Headphones"], Clothing: ["Shirt", "Pants"] }

Remove Duplicates

const items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const unique = items.reduce((acc, item) => {
  if (!acc.includes(item)) acc.push(item);
  return acc;
}, []);
// ["apple", "banana", "orange"]

// Simpler approach with Set:
const unique2 = [...new Set(items)];

Count Occurrences

const words = ['hello', 'world', 'hello', 'javascript', 'world', 'hello'];
const counts = words.reduce((acc, word) => {
  acc[word] = (acc[word] || 0) + 1;
  return acc;
}, {});
// { hello: 3, world: 2, javascript: 1 }

Flatten Nested Arrays (without flat)

const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
// [1, 2, 3, 4, 5, 6]
💡 Tip: Always provide an initial value (the second argument) to reduce(). Without it, the first element becomes the accumulator, which can cause unexpected behavior with empty arrays.

3. Searching Methods

Array.prototype.find() Popular

Returns the first element that matches a condition, or undefined if no match is found.

const users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob', role: 'user' },
  { id: 3, name: 'Charlie', role: 'admin' }
];

const admin = users.find(u => u.role === 'admin');
// { id: 1, name: 'Alice', role: 'admin' }

Array.prototype.findIndex()

Like find(), but returns the index instead of the element.

const numbers = [10, 20, 30, 40, 50];
const index = numbers.findIndex(n => n > 25);
// 2

Array.prototype.indexOf()

Finds the index of the first occurrence of a specific value. Works with primitive values (not objects).

const fruits = ['apple', 'banana', 'orange', 'banana'];
fruits.indexOf('banana');  // 1
fruits.indexOf('grape');    // -1 (not found)
fruits.lastIndexOf('banana'); // 3

Array.prototype.includes()

Checks if an array contains a value. Returns true or false. Simpler than indexOf() >= 0.

const colors = ['red', 'green', 'blue'];
colors.includes('green');   // true
colors.includes('yellow'); // false

// Practical use: check permissions
const userPermissions = ['read', 'write'];
const canDelete = userPermissions.includes('delete'); // false

4. Transformation Methods

Array.prototype.flat() ES2019

Flattens nested arrays. Pass a depth argument to control how deep to flatten.

const deeply = [1, [2, 3], [4, [5, 6]]];
deeply.flat();       // [1, 2, 3, 4, [5, 6]]
deeply.flat(2);      // [1, 2, 3, 4, 5, 6]
deeply.flat(Infinity); // [1, 2, 3, 4, 5, 6] (flatten all levels)

Array.prototype.flatMap() ES2019

Maps each element, then flattens the result by one level. More efficient than map().flat().

const sentences = ["Hello world", "Good morning everyone"];
const words = sentences.flatMap(s => s.split(' '));
// ["Hello", "world", "Good", "morning", "everyone"]

// Create pairs from elements
const numbers = [1, 2, 3];
const pairs = numbers.flatMap(n => [n, n * 10]);
// [1, 10, 2, 20, 3, 30]

Array.prototype.join()

Joins all elements into a string with a separator.

const tags = ['javascript', 'react', 'nodejs'];
tags.join(', ');          // "javascript, react, nodejs"
tags.join(' | ');         // "javascript | react | nodejs"
tags.join('');            // "javascriptreactnodejs"
[2025, 6, 15].join('-');  // "2025-6-15"

Array.prototype.slice()

Returns a shallow copy of a portion of an array. Does not modify the original.

const arr = [1, 2, 3, 4, 5];
arr.slice(1, 3);    // [2, 3] (from index 1, up to but not including 3)
arr.slice(-2);       // [4, 5] (last 2 elements)
arr.slice(2);         // [3, 4, 5] (from index 2 to end)
arr.slice();          // [1, 2, 3, 4, 5] (full copy)

Array.prototype.concat()

const a = [1, 2], b = [3, 4], c = [5, 6];
const merged = a.concat(b, c); // [1, 2, 3, 4, 5, 6]
// Modern alternative:
const merged2 = [...a, ...b, ...c];

5. Sorting Methods

Array.prototype.sort()

Important: sort() mutates the original array and sorts elements as strings by default.

const numbers = [10, 1, 21, 2];
numbers.sort(); // [1, 10, 2, 21] — WRONG! (sorted as strings)

// Correct numeric sort:
numbers.sort((a, b) => a - b); // [1, 2, 10, 21] ascending
numbers.sort((a, b) => b - a); // [21, 10, 2, 1] descending

// Sort objects by property:
const users = [
  { name: 'Charlie', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
];
users.sort((a, b) => a.age - b.age);
// Sorted by age ascending

// Sort strings case-insensitively:
const names = ['alice', 'Bob', 'charlie', 'David'];
names.sort((a, b) => a.localeCompare(b));
// ["alice", "Bob", "charlie", "David"]

Array.prototype.toSorted() ES2023

Same as sort() but returns a new array without mutating the original.

const original = [3, 1, 4, 1, 5];
const sorted = original.toSorted((a, b) => a - b);
// original: [3, 1, 4, 1, 5] — unchanged!
// sorted:   [1, 1, 3, 4, 5]

Array.prototype.toReversed() ES2023

const arr = [1, 2, 3];
const reversed = arr.toReversed();
// arr: [1, 2, 3] — unchanged
// reversed: [3, 2, 1]

6. Mutation Methods (Add/Remove Elements)

MethodModifies?Description
push()✅ YesAdd element(s) to the end
pop()✅ YesRemove last element
unshift()✅ YesAdd element(s) to the beginning
shift()✅ YesRemove first element
splice()✅ YesInsert/remove elements at any index
const arr = [1, 2, 3];

// Add to end
arr.push(4);         // [1, 2, 3, 4]
arr.push(5, 6);     // [1, 2, 3, 4, 5, 6]

// Remove from end
arr.pop();          // [1, 2, 3, 4, 5] — returns 6

// Add to beginning
arr.unshift(0);     // [0, 1, 2, 3, 4, 5]

// Remove from beginning
arr.shift();        // [1, 2, 3, 4, 5] — returns 0

// splice: insert at index 2, remove 0 items, insert 'a' and 'b'
arr.splice(2, 0, 'a', 'b'); // [1, 2, 'a', 'b', 3, 4, 5]

// splice: remove 2 items starting at index 1
arr.splice(1, 2);          // [1, 'b', 3, 4, 5]

7. New Immutable Methods (ES2023)

ES2023 introduced immutable versions of popular mutating methods. These create new arrays instead of modifying the original.

Array.prototype.toSpliced()

const months = ['Jan', 'Mar', 'Apr', 'May'];

// Insert 'Feb' at index 1, remove 0 items
const withFeb = months.toSpliced(1, 0, 'Feb');
// withFeb: ['Jan', 'Feb', 'Mar', 'Apr', 'May']
// months: ['Jan', 'Mar', 'Apr', 'May'] — unchanged!

Array.prototype.with()

const colors = ['red', 'green', 'blue'];
const updated = colors.with(1, 'yellow');
// updated: ['red', 'yellow', 'blue']
// colors: ['red', 'green', 'blue'] — unchanged!

8. Array.from, Array.of & Set Operations

Array.from()

// From a string
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']

// From a NodeList (query selector results)
Array.from(document.querySelectorAll('.item'));

// With a mapping function
Array.from({ length: 5 }, (_, i) => i + 1); // [1, 2, 3, 4, 5]

// Generate a range
Array.from({ length: 10 }, (_, i) => i * i); // [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Array.of()

Array.of(1, 2, 3);    // [1, 2, 3]
Array.of('hello');      // ['hello']
// vs. Array() with a single number:
Array(3);               // [empty × 3] — NOT what you might expect!
Array.of(3);            // [3] — correct!

Set Operations (Union, Intersection, Difference)

const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);

// Union
const union = new Set([...a, ...b]);
// Set {1, 2, 3, 4, 5, 6}

// Intersection
const intersection = new Set([...a].filter(x => b.has(x)));
// Set {3, 4}

// Difference (in a but not in b)
const difference = new Set([...a].filter(x => !b.has(x)));
// Set {1, 2}

9. Common Patterns & Best Practices

Chain map → filter → reduce

The real power of array methods comes from chaining them together:

const orders = [
  { product: 'Laptop', price: 999, quantity: 2, category: 'Electronics' },
  { product: 'Book', price: 15, quantity: 5, category: 'Education' },
  { product: 'Phone', price: 699, quantity: 1, category: 'Electronics' },
  { product: 'Pen', price: 2, quantity: 100, category: 'Education' },
  { product: 'Tablet', price: 499, quantity: 3, category: 'Electronics' }
];

// Total revenue from Electronics
const electronicsRevenue = orders
  .filter(order => order.category === 'Electronics')
  .map(order => order.price * order.quantity)
  .reduce((sum, total) => sum + total, 0);
// (999*2) + (699*1) + (499*3) = 1998 + 699 + 1497 = 4194

Convert query parameters

const params = new URLSearchParams('page=1&sort=name&filter=active');
const paramArray = Array.from(params.entries());
// [["page", "1"], ["sort", "name"], ["filter", "active"]]

const paramObject = Object.fromEntries(params);
// { page: "1", sort: "name", filter: "active" }

For URL encoding/decoding, try our URL Encoder/Decoder tool.

Debounce search with filter

const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape'];

function searchItems(query) {
  if (!query) return items;
  return items.filter(item =>
    item.toLowerCase().includes(query.toLowerCase())
  );
}

searchItems('a');   // ["Apple", "Banana", "Date", "Elderberry", "Grape"]
searchItems('e');   // ["Cherry", "Date", "Elderberry", "Fig"]
searchItems('berry'); // ["Elderberry"]

Paginate with slice

const allItems = [...Array(100).keys()].map(i => `Item ${i + 1}`);

function paginate(items, page = 1, perPage = 10) {
  const start = (page - 1) * perPage;
  const end = start + perPage;
  return {
    data: items.slice(start, end),
    page,
    totalPages: Math.ceil(items.length / perPage),
    total: items.length
  };
}

paginate(allItems, 3, 10);
// { data: ["Item 21", ..., "Item 30"], page: 3, totalPages: 10, total: 100 }

10. Performance Tips

  1. Prefer for...of or forEach for maximum performance when you don't need a new array. map() and filter() create new arrays which costs memory.
  2. Avoid Array.isArray() inside tight loops — check types once before the loop.
  3. Use Set for lookups — Set.has() is O(1) vs Array.includes() O(n).
  4. Don't chain too many methods — each method in the chain iterates the full array. For very large arrays, a single for loop can be faster.
  5. Use at() for negative indexing (ES2022) instead of arr[arr.length - 1]:
const arr = [10, 20, 30];
arr.at(-1); // 30 (last element)
arr.at(-2); // 20 (second from last)

Quick Reference Table

MethodReturnsModifies OriginalMutates?
map()New arrayNo❌
filter()New arrayNo❌
reduce()Single valueNo❌
find()Element or undefinedNo❌
sort()Same arrayYes✅
toSorted()New arrayNo❌
push()/pop()Length / elementYes✅
splice()Removed elementsYes✅
toSpliced()New arrayNo❌
slice()New array (copy)No❌
concat()New arrayNo❌
flat()New arrayNo❌
forEach()undefinedNo❌

Conclusion

JavaScript array methods are incredibly expressive and powerful. Mastering map, filter, reduce, find, and the newer immutable methods like toSorted() and with() will level up your code quality. Practice chaining methods, understand which ones mutate vs. create new arrays, and use the right tool for each job.

For more developer resources, explore the Hedpy Blog or check out our free online developer tools.

🛠️ 推荐工具

免费在线开发工具,浏览器直接使用

前往工具站 → nbsp; AI API接口 →