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.
Iteration methods let you loop through array elements and apply transformations, filters, or execute side effects.
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"]
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 }]
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}...`);
});
map() or filter() over forEach() when you need a return value. Use forEach() for side effects like logging or DOM manipulation.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
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.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
// 15
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"] }
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)];
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 }
const nested = [[1, 2], [3, 4], [5, 6]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
// [1, 2, 3, 4, 5, 6]
reduce(). Without it, the first element becomes the accumulator, which can cause unexpected behavior with empty arrays.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' }
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
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
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
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)
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]
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"
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)
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];
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"]
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]
const arr = [1, 2, 3];
const reversed = arr.toReversed();
// arr: [1, 2, 3] — unchanged
// reversed: [3, 2, 1]
| Method | Modifies? | Description |
|---|---|---|
| push() | ✅ Yes | Add element(s) to the end |
| pop() | ✅ Yes | Remove last element |
| unshift() | ✅ Yes | Add element(s) to the beginning |
| shift() | ✅ Yes | Remove first element |
| splice() | ✅ Yes | Insert/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]
ES2023 introduced immutable versions of popular mutating methods. These create new arrays instead of modifying the original.
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!
const colors = ['red', 'green', 'blue'];
const updated = colors.with(1, 'yellow');
// updated: ['red', 'yellow', 'blue']
// colors: ['red', 'green', 'blue'] — unchanged!
// 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(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!
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}
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
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.
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"]
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 }
for...of or forEach for maximum performance when you don't need a new array. map() and filter() create new arrays which costs memory.Array.isArray() inside tight loops — check types once before the loop.Set for lookups — Set.has() is O(1) vs Array.includes() O(n).for loop can be faster.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)
| Method | Returns | Modifies Original | Mutates? |
|---|---|---|---|
| map() | New array | No | ❌ |
| filter() | New array | No | ❌ |
| reduce() | Single value | No | ❌ |
| find() | Element or undefined | No | ❌ |
| sort() | Same array | Yes | ✅ |
| toSorted() | New array | No | ❌ |
| push()/pop() | Length / element | Yes | ✅ |
| splice() | Removed elements | Yes | ✅ |
| toSpliced() | New array | No | ❌ |
| slice() | New array (copy) | No | ❌ |
| concat() | New array | No | ❌ |
| flat() | New array | No | ❌ |
| forEach() | undefined | No | ❌ |
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接口 →