JavaScript arrays come with powerful built-in methods that can transform how you handle data. Instead of writing complex loops, leverage these methods to write cleaner, more readable code.
This guide covers the most useful array methods with practical examples. Each method includes a description, syntax, and real-world use case.
Try out the examples in your browser console or copy them into your projects!
Creates a new array by applying a function to each element of the original array.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
Use case: Transform API responses, format data for display.
Creates a new array with elements that pass a test function.
const users = [
{name: "Alice", age: 25},
{name: "Bob", age: 17}
];
const adults = users.filter(u => u.age >= 18);
Use case: Search functionality, data filtering in applications.
Reduces an array to a single value by applying a function against an accumulator.
const expenses = [100, 250, 75, 300];
const total = expenses.reduce((sum, expense) => sum + expense, 0);
Use case: Calculating totals, grouping data, flattening arrays.
Returns the first element that satisfies a provided testing function.
const products = [
{id: 1, name: "Laptop"},
{id: 2, name: "Phone"}
];
const product = products.find(p => p.id === 2);
Use case: Finding specific items in collections, user lookups.
Check if all (every) or any (some) elements pass a test.
const scores = [85, 92, 78, 96];
const allPassed = scores.every(s => s >= 70); // true
const hasHighScore = scores.some(s => s > 95); // true
Use case: Form validation, permission checks, condition verification.
Sorts the elements of an array in place and returns the sorted array.
const fruits = ["banana", "apple", "cherry"];
fruits.sort(); // Alphabetical
const numbers = [3, 1, 4, 1, 5];
numbers.sort((a, b) => a - b); // Numerical
// [1, 1, 3, 4, 5]
Use case: Displaying ordered lists, ranking systems, data organization.