A practical guide to JavaScript array methods, from map(), filter(), and reduce() to find(), some(), every(), sort(), and modern immutable methods.
JavaScript Array Methods: The Complete Guide to map(), filter(), reduce(), and More
Arrays are one of the most fundamental data structures in JavaScript.
Whether you're building a React application, working with APIs, filtering products, or managing user data, you'll constantly work with arrays.
Imagine receiving this data from an API:
const users = [
{ id: 1, name: "Alice", age: 25, active: true },
{ id: 2, name: "Bob", age: 17, active: false },
{ id: 3, name: "Charlie", age: 30, active: true },
{ id: 4, name: "David", age: 22, active: false },
];
You might want to:
- Extract all user names.
- Find users older than 18.
- Calculate the average age.
- Find a specific user.
- Check whether at least one user is active.
- Sort users by age.
JavaScript provides powerful built-in array methods to accomplish these tasks without writing unnecessary loops.
Let's explore the most important ones.
1. map() — Transform Every Element
The map() method creates a new array by applying a callback function to every element of the original array.
It does not modify the original array.
Syntax
array.map((element, index, array) => {
return newValue;
});
The callback receives:
-
element: The current element. -
index: The current element's index. -
array: The original array.
Example
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => {
return number * 2;
});
console.log(doubled);
// [2, 4, 6, 8, 10]
console.log(numbers);
// [1, 2, 3, 4, 5]
A shorter syntax
When your callback contains a single expression, you can use an arrow function:
const doubled = numbers.map((number) => number * 2);
Real-world example
Imagine displaying user names from API data:
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
const names = users.map((user) => user.name);
console.log(names);
// ["Alice", "Bob", "Charlie"]
map() in React
One of the most common uses of map() is rendering lists of components:
function UserList({ users }) {
return (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name}
</li>
))}
</ul>
);
}
Remember: Use map() when you want to transform every element into something else.
2. filter() — Select Elements Based on a Condition
The filter() method creates a new array containing only the elements that satisfy a condition.
The callback must return a truthy or falsy value.
Example
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((number) => {
return number % 2 === 0;
});
console.log(evenNumbers);
// [2, 4, 6]
Only numbers that satisfy the condition are included.
Real-world example
Filtering active users:
const users = [
{ name: "Alice", active: true },
{ name: "Bob", active: false },
{ name: "Charlie", active: true },
];
const activeUsers = users.filter((user) => user.active);
console.log(activeUsers);
// Alice and Charlie
Filtering products by price
const products = [
{ name: "Laptop", price: 1200 },
{ name: "Mouse", price: 25 },
{ name: "Keyboard", price: 75 },
];
const affordableProducts = products.filter(
(product) => product.price < 100
);
console.log(affordableProducts);
// Mouse and Keyboard
Remember: Use filter() when you want to keep some elements and remove others.
3. reduce() — Reduce an Array to a Single Value
The reduce() method executes a callback for every element and accumulates the result into a single value.
That value can be:
- A number.
- A string.
- An object.
- Another array.
- Any other JavaScript value.
Syntax
array.reduce((accumulator, currentValue) => {
return updatedAccumulator;
}, initialValue);
The two most important parameters are:
-
accumulator: The accumulated result. -
currentValue: The current element being processed.
Example: Calculate the total
const prices = [10, 20, 30, 40];
const total = prices.reduce((sum, price) => {
return sum + price;
}, 0);
console.log(total);
// 100
Let's understand what happens:
| Iteration | Accumulator | Current Value | Result |
|---|---|---|---|
| 1 | 0 | 10 | 10 |
| 2 | 10 | 20 | 30 |
| 3 | 30 | 30 | 60 |
| 4 | 60 | 40 | 100 |
The final accumulator becomes the result.
Shorter syntax
const total = prices.reduce(
(sum, price) => sum + price,
0
);
Example: Count occurrences
const fruits = [
"apple",
"banana",
"apple",
"orange",
"banana",
"apple",
];
const fruitCount = fruits.reduce((count, fruit) => {
count[fruit] = (count[fruit] || 0) + 1;
return count;
}, {});
console.log(fruitCount);
// {
// apple: 3,
// banana: 2,
// orange: 1
// }
Example: Calculate the total price of a shopping cart
const cart = [
{ name: "Laptop", price: 1000, quantity: 1 },
{ name: "Mouse", price: 50, quantity: 2 },
{ name: "Keyboard", price: 100, quantity: 1 },
];
const totalPrice = cart.reduce((total, item) => {
return total + item.price * item.quantity;
}, 0);
console.log(totalPrice);
// 1200
Remember: Use reduce() when you want to accumulate values or transform an array into a single result.
Always consider providing an initial value, especially when working with potentially empty arrays.
4. forEach() — Execute a Function for Every Element
The forEach() method executes a callback for each element.
Unlike map(), it does not return a new array.
Example
const numbers = [1, 2, 3];
numbers.forEach((number) => {
console.log(number);
});
// 1
// 2
// 3
Practical example
const users = ["Alice", "Bob", "Charlie"];
users.forEach((user) => {
console.log(`Welcome, ${user}!`);
});
forEach() vs. map()
const numbers = [1, 2, 3];
const result1 = numbers.map((number) => number * 2);
const result2 = numbers.forEach((number) => number * 2);
console.log(result1);
// [2, 4, 6]
console.log(result2);
// undefined
Remember: Use forEach() for side effects, such as logging or calling a function. Use map() when you need a transformed array.
5. find() — Find the First Matching Element
The find() method returns the first element that satisfies a condition.
If no element matches, it returns undefined.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
const user = users.find((user) => user.id === 2);
console.log(user);
// { id: 2, name: "Bob" }
Important difference
find() returns the element itself, not an array.
const numbers = [10, 20, 30, 40];
const result = numbers.find((number) => number > 20);
console.log(result);
// 30
6. findIndex() — Find the Index of an Element
The findIndex() method returns the index of the first element that satisfies a condition.
If no match is found, it returns -1.
const numbers = [10, 20, 30, 40];
const index = numbers.findIndex((number) => number === 30);
console.log(index);
// 2
find() vs. findIndex()
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
const user = users.find((user) => user.id === 2);
const index = users.findIndex((user) => user.id === 2);
console.log(user);
// { id: 2, name: "Bob" }
console.log(index);
// 1
7. some() — Does at Least One Element Match?
The some() method returns true if at least one element satisfies the condition.
Otherwise, it returns false.
const numbers = [1, 3, 5, 8];
const hasEvenNumber = numbers.some((number) => number % 2 === 0);
console.log(hasEvenNumber);
// true
Real-world example
const users = [
{ name: "Alice", admin: false },
{ name: "Bob", admin: true },
{ name: "Charlie", admin: false },
];
const hasAdmin = users.some((user) => user.admin);
console.log(hasAdmin);
// true
8. every() — Do All Elements Match?
The every() method returns true only if every element satisfies the condition.
const numbers = [2, 4, 6, 8];
const allEven = numbers.every((number) => number % 2 === 0);
console.log(allEven);
// true
Example
const ages = [21, 25, 30];
const allAdults = ages.every((age) => age >= 18);
console.log(allAdults);
// true
some() vs. every()
| Method | Meaning |
|---|---|
some() |
At least one element matches |
every() |
Every element matches |
9. includes() — Check Whether an Array Contains a Value
The includes() method checks whether an array contains a specific value.
const fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana"));
// true
console.log(fruits.includes("grape"));
// false
Example
const permissions = ["read", "write", "delete"];
const canDelete = permissions.includes("delete");
console.log(canDelete);
// true
For primitive values, includes() uses SameValueZero comparison. For objects, it checks reference identity rather than comparing their properties.
10. indexOf() — Find the Position of a Value
The indexOf() method returns the index of the first occurrence of a value.
If the value doesn't exist, it returns -1.
const fruits = ["apple", "banana", "orange"];
console.log(fruits.indexOf("banana"));
// 1
console.log(fruits.indexOf("grape"));
// -1
Example
const numbers = [10, 20, 30, 20];
console.log(numbers.indexOf(20));
// 1
Unlike findIndex(), indexOf() searches for a value directly rather than using a callback.
11. slice() — Extract a Portion of an Array
The slice() method returns a shallow copy of a portion of an array.
It does not modify the original array.
Syntax
array.slice(start, end);
The end index is excluded.
const numbers = [10, 20, 30, 40, 50];
const result = numbers.slice(1, 4);
console.log(result);
// [20, 30, 40]
Negative indexes
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.slice(-2));
// [40, 50]
Example: Get the first three elements
const numbers = [1, 2, 3, 4, 5];
const firstThree = numbers.slice(0, 3);
console.log(firstThree);
// [1, 2, 3]
12. splice() — Add, Remove, or Replace Elements
Unlike slice(), the splice() method modifies the original array.
Remove elements
const fruits = ["apple", "banana", "orange", "grape"];
fruits.splice(1, 2);
console.log(fruits);
// ["apple", "grape"]
The first argument specifies the starting index.
The second argument specifies how many elements to remove.
Add elements
const fruits = ["apple", "orange"];
fruits.splice(1, 0, "banana");
console.log(fruits);
// ["apple", "banana", "orange"]
Replace elements
const fruits = ["apple", "banana", "orange"];
fruits.splice(1, 1, "grape");
console.log(fruits);
// ["apple", "grape", "orange"]
Remember: splice() mutates the original array.
13. sort() — Sort Array Elements
The sort() method sorts an array in place.
By default, JavaScript sorts elements as strings.
The problem with default sorting
const numbers = [10, 5, 100, 25];
numbers.sort();
console.log(numbers);
// [10, 100, 25, 5]
This happens because the default sort compares string representations.
Correct numeric sorting
const numbers = [10, 5, 100, 25];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [5, 10, 25, 100]
Descending order
const numbers = [10, 5, 100, 25];
numbers.sort((a, b) => b - a);
console.log(numbers);
// [100, 25, 10, 5]
Sorting objects
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 18 },
{ name: "Charlie", age: 30 },
];
users.sort((a, b) => a.age - b.age);
console.log(users);
This sorts users by age in ascending order.
14. flat() — Flatten Nested Arrays
The flat() method creates a new array with nested arrays flattened to a specified depth.
const numbers = [1, [2, 3], [4, 5]];
console.log(numbers.flat());
// [1, 2, 3, 4, 5]
Flatten multiple levels
const numbers = [1, [2, [3, [4]]]];
console.log(numbers.flat(2));
// [1, 2, 3, [4]]
Flatten completely
const numbers = [1, [2, [3, [4]]]];
console.log(numbers.flat(Infinity));
// [1, 2, 3, 4]
15. flatMap() — Map and Flatten in One Operation
The flatMap() method combines map() with flat(1).
const numbers = [1, 2, 3];
const result = numbers.flatMap((number) => [number, number * 2]);
console.log(result);
// [1, 2, 2, 4, 3, 6]
Example
const sentences = ["Hello world", "JavaScript is awesome"];
const words = sentences.flatMap((sentence) => sentence.split(" "));
console.log(words);
// ["Hello", "world", "JavaScript", "is", "awesome"]
16. concat() — Combine Arrays
The concat() method creates a new array by combining arrays or values.
const first = [1, 2, 3];
const second = [4, 5, 6];
const combined = first.concat(second);
console.log(combined);
// [1, 2, 3, 4, 5, 6]
You can also use the spread operator:
const combined = [...first, ...second];
17. join() — Convert an Array Into a String
The join() method combines array elements into a string.
const fruits = ["apple", "banana", "orange"];
console.log(fruits.join(", "));
// "apple, banana, orange"
Example
const words = ["JavaScript", "is", "awesome"];
console.log(words.join(" "));
// "JavaScript is awesome"
18. push() and pop() — Work With the End of an Array
push()
Adds one or more elements to the end of an array.
const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers);
// [1, 2, 3, 4]
pop()
Removes the last element and returns it.
const numbers = [1, 2, 3];
const removed = numbers.pop();
console.log(removed);
// 3
console.log(numbers);
// [1, 2]
Both methods mutate the original array.
19. shift() and unshift() — Work With the Beginning of an Array
shift()
Removes the first element.
const numbers = [1, 2, 3];
numbers.shift();
console.log(numbers);
// [2, 3]
unshift()
Adds elements to the beginning.
const numbers = [2, 3];
numbers.unshift(1);
console.log(numbers);
// [1, 2, 3]
Both methods mutate the original array.
20. Modern Immutable Array Methods
Modern JavaScript also provides methods that return modified copies without changing the original array.
These methods are particularly useful when working with React state.
toSorted()
Returns a sorted copy.
const numbers = [3, 1, 2];
const sorted = numbers.toSorted((a, b) => a - b);
console.log(sorted);
// [1, 2, 3]
console.log(numbers);
// [3, 1, 2]
toReversed()
Returns a reversed copy.
const numbers = [1, 2, 3];
const reversed = numbers.toReversed();
console.log(reversed);
// [3, 2, 1]
toSpliced()
Returns a copy with elements removed, replaced, or inserted.
const numbers = [1, 2, 3, 4];
const result = numbers.toSpliced(1, 2, 99);
console.log(result);
// [1, 99, 4]
console.log(numbers);
// [1, 2, 3, 4]
with()
Returns a copy with one element replaced.
const numbers = [10, 20, 30];
const updated = numbers.with(1, 99);
console.log(updated);
// [10, 99, 30]
console.log(numbers);
// [10, 20, 30]
These methods are supported in modern JavaScript environments. Check compatibility if you're targeting older browsers.
21. The Most Important Difference: Mutating vs. Non-Mutating Methods
Understanding which methods modify the original array is essential.
| Method | Returns | Mutates Original? |
|---|---|---|
map() |
New array | No |
filter() |
New array | No |
reduce() |
Accumulated value | No |
forEach() |
undefined |
No |
find() |
Element or undefined
|
No |
findIndex() |
Index or -1
|
No |
some() |
Boolean | No |
every() |
Boolean | No |
slice() |
New array | No |
concat() |
New array | No |
flat() |
New array | No |
flatMap() |
New array | No |
sort() |
Sorted array | Yes |
reverse() |
Reversed array | Yes |
splice() |
Removed elements | Yes |
push() |
New length | Yes |
pop() |
Removed element | Yes |
shift() |
Removed element | Yes |
unshift() |
New length | Yes |
toSorted() |
New array | No |
toReversed() |
New array | No |
toSpliced() |
New array | No |
with() |
New array | No |
22. Which Method Should You Use?
Here's a practical cheat sheet:
| Goal | Method |
|---|---|
| Transform every element | map() |
| Select matching elements | filter() |
| Calculate a total | reduce() |
| Execute a function for every element | forEach() |
| Find the first matching element | find() |
| Find an element's index | findIndex() |
| Check whether at least one matches | some() |
| Check whether all match | every() |
| Check whether a value exists | includes() |
| Find a value's position | indexOf() |
| Extract part of an array | slice() |
| Add or remove elements in place | splice() |
| Sort an array | sort() |
| Flatten nested arrays | flat() |
| Transform and flatten | flatMap() |
| Combine arrays | concat() |
| Convert an array into a string | join() |
Final Thoughts
JavaScript array methods are more than convenient shortcuts. They help you write code that is easier to read, maintain, and reason about.
If you're learning React, these methods become especially important because you'll frequently transform API data, filter lists, calculate values, and render components.
Start by mastering these five methods:
map()filter()reduce()find()some()
Once you understand them deeply, many everyday JavaScript problems become much easier.
The best way to learn these methods is to practice them with real data rather than memorize their syntax.
Which array method do you use the most in your JavaScript projects?
Share your thoughts in the comments!
Top comments (0)