JavaScript Array Methods Cheat Sheet — Complete Guide with Example
JavaScript arrays come with a surprisingly rich set of built-in methods
— and knowing them well is what separates developers who write clean,
expressive code from those who reach for a for loop every
time. Whether you are filtering a list of users, transforming API
responses, finding a specific record, or flattening nested data, there
is almost always an array method built for exactly that job.
This is your complete reference guide to JavaScript array methods — every method you need to know, clearly explained with real examples, organised by what you are trying to do. Bookmark this page. You will come back to it.
1. Adding and Removing Elements
These are the most basic array operations — adding items to and removing items from an array.
const fruits = ["apple", "banana"];
// push() — add to the END, returns new length
fruits.push("mango");
// ["apple", "banana", "mango"]
// pop() — remove from the END, returns removed element
const last = fruits.pop();
// last = "mango", fruits = ["apple", "banana"]
// unshift() — add to the BEGINNING, returns new length
fruits.unshift("strawberry");
// ["strawberry", "apple", "banana"]
// shift() — remove from the BEGINNING, returns removed element
const first = fruits.shift();
// first = "strawberry", fruits = ["apple", "banana"]
// splice(start, deleteCount, ...items) — add/remove anywhere
fruits.splice(1, 0, "grape"); // insert "grape" at index 1
// ["apple", "grape", "banana"]
fruits.splice(1, 1); // remove 1 element at index 1
// ["apple", "banana"]
fruits.splice(1, 1, "kiwi", "pear"); // replace 1 element with 2
// ["apple", "kiwi", "pear"]
2. Searching and Finding
Find specific elements or check if they exist in an array.
const numbers = [10, 20, 30, 40, 50];
const users = [
{ id: 1, name: "Randhir", active: true },
{ id: 2, name: "Priya", active: false },
{ id: 3, name: "Amit", active: true },
];
// indexOf() — returns index of first match, -1 if not found
numbers.indexOf(30); // 2
numbers.indexOf(99); // -1
// includes() — returns true/false
numbers.includes(20); // true
numbers.includes(99); // false
// find() — returns FIRST element that matches condition
const user = users.find(u => u.id === 2);
// { id: 2, name: "Priya", active: false }
// findIndex() — returns INDEX of first match, -1 if not found
const index = users.findIndex(u => u.name === "Amit");
// 2
// findLast() — returns LAST element that matches (ES2023)
const lastActive = users.findLast(u => u.active === true);
// { id: 3, name: "Amit", active: true }
// some() — true if AT LEAST ONE element matches
users.some(u => u.active === false); // true
// every() — true if ALL elements match
users.every(u => u.active === true); // false
3. Transforming Arrays
Create new arrays by transforming, filtering, or reducing existing ones. These are the methods you will use most in real projects.
const numbers = [1, 2, 3, 4, 5];
const products = [
{ name: "Laptop", price: 75000, category: "Electronics" },
{ name: "Chair", price: 5000, category: "Furniture" },
{ name: "Phone", price: 25000, category: "Electronics" },
{ name: "Desk", price: 8000, category: "Furniture" },
];
// map() — transform every element, returns new array of same length
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
const names = products.map(p => p.name);
// ["Laptop", "Chair", "Phone", "Desk"]
const withTax = products.map(p => ({
...p,
priceWithTax: p.price * 1.18
}));
// Each product now has a priceWithTax property added
// filter() — keep only elements that match condition
const expensive = products.filter(p => p.price > 10000);
// [{ name: "Laptop", price: 75000 }, { name: "Phone", price: 25000 }]
const electronics = products.filter(p => p.category === "Electronics");
// reduce() — reduce array to a single value
const total = products.reduce((sum, p) => sum + p.price, 0);
// 113000
// Build an object from an array using reduce
const priceMap = products.reduce((acc, p) => {
acc[p.name] = p.price;
return acc;
}, {});
// { Laptop: 75000, Chair: 5000, Phone: 25000, Desk: 8000 }
// Count items by category
const countByCategory = products.reduce((acc, p) => {
acc[p.category] = (acc[p.category] || 0) + 1;
return acc;
}, {});
// { Electronics: 2, Furniture: 2 }
4. Sorting and Reversing
Sort arrays in any order. The default sort() behaviour
surprises most developers — always provide a compare function.
const numbers = [10, 1, 5, 30, 2];
const names = ["Randhir", "Priya", "Amit", "Neha"];
// sort() — sorts IN PLACE, modifies original array
// ⚠️ Default sort converts to strings — wrong for numbers!
[10, 1, 5, 30, 2].sort();
// [1, 10, 2, 30, 5] — WRONG for numbers (sorted alphabetically)
// ✅ Correct — always use compare function for numbers
numbers.sort((a, b) => a - b); // ascending: [1, 2, 5, 10, 30]
numbers.sort((a, b) => b - a); // descending: [30, 10, 5, 2, 1]
// Sort strings alphabetically
names.sort(); // ["Amit", "Neha", "Priya", "Randhir"]
names.sort((a, b) => b.localeCompare(a)); // reverse alphabetical
// Sort objects by a property
const products = [
{ name: "Laptop", price: 75000 },
{ name: "Chair", price: 5000 },
{ name: "Phone", price: 25000 },
];
products.sort((a, b) => a.price - b.price);
// Chair (5000), Phone (25000), Laptop (75000)
products.sort((a, b) => a.name.localeCompare(b.name));
// Alphabetical by name
// ✅ Sort without mutating — use spread to copy first
const sorted = [...products].sort((a, b) => a.price - b.price);
// products is unchanged, sorted has the sorted version
// reverse() — reverses IN PLACE
[1, 2, 3, 4, 5].reverse();
// [5, 4, 3, 2, 1]
5. Combining and Slicing
const a = [1, 2, 3];
const b = [4, 5, 6];
// concat() — merge arrays, returns new array
const merged = a.concat(b);
// [1, 2, 3, 4, 5, 6]
// Spread operator — cleaner alternative to concat
const merged2 = [...a, ...b];
// [1, 2, 3, 4, 5, 6]
// Add items while merging
const merged3 = [...a, 99, ...b, 100];
// [1, 2, 3, 99, 4, 5, 6, 100]
// slice(start, end) — extract a portion, does NOT mutate original
const arr = [10, 20, 30, 40, 50];
arr.slice(1, 3); // [20, 30] — from index 1 up to (not including) 3
arr.slice(2); // [30, 40, 50] — from index 2 to end
arr.slice(-2); // [40, 50] — last 2 elements
arr.slice(0, -1); // [10, 20, 30, 40] — all except last
// Original array is unchanged
console.log(arr); // [10, 20, 30, 40, 50]
6. Flattening Arrays
These methods are essential when working with nested arrays — common when processing API responses or grouping data.
// flat() — flatten one level deep by default
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6]
nested.flat(Infinity); // flatten all levels regardless of depth
// flatMap() — map() then flat(1) in one step
const sentences = ["Hello world", "Foo bar"];
const words = sentences.flatMap(s => s.split(" "));
// ["Hello", "world", "Foo", "bar"]
// Real world — flatten orders from multiple users
const users = [
{ name: "Randhir", orders: ["laptop", "phone"] },
{ name: "Priya", orders: ["chair", "desk"] },
];
const allOrders = users.flatMap(u => u.orders);
// ["laptop", "phone", "chair", "desk"]
7. Iteration Methods
const fruits = ["apple", "banana", "mango"];
// forEach() — loop through array, no return value
fruits.forEach((fruit, index) => {
console.log(index + ": " + fruit);
});
// 0: apple
// 1: banana
// 2: mango
// entries() — loop with index AND value
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}
// keys() — loop through indices only
for (const index of fruits.keys()) {
console.log(index); // 0, 1, 2
}
// values() — loop through values only
for (const fruit of fruits.values()) {
console.log(fruit); // apple, banana, mango
}
8. Converting Arrays
// join() — array to string with separator
["apple", "banana", "mango"].join(", ");
// "apple, banana, mango"
["Hello", "World"].join(" ");
// "Hello World"
[1, 2, 3].join("-");
// "1-2-3"
// toString() — array to comma-separated string
[1, 2, 3].toString();
// "1,2,3"
// Array.from() — convert iterable to array
Array.from("hello");
// ["h", "e", "l", "l", "o"]
Array.from({ length: 5 }, (_, i) => i + 1);
// [1, 2, 3, 4, 5]
Array.from(new Set([1, 2, 2, 3, 3]));
// [1, 2, 3] — remove duplicates using Set
// Array.of() — create array from arguments
Array.of(1, 2, 3);
// [1, 2, 3]
// isArray() — check if something is an array
Array.isArray([1, 2, 3]); // true
Array.isArray("hello"); // false
Array.isArray({ a: 1 }); // false
9. Filling and Copying
// fill(value, start, end) — fill positions with a value
[1, 2, 3, 4, 5].fill(0); // [0, 0, 0, 0, 0]
[1, 2, 3, 4, 5].fill(0, 2, 4); // [1, 2, 0, 0, 5]
// Create an array of zeros
new Array(5).fill(0); // [0, 0, 0, 0, 0]
// copyWithin(target, start, end) — copy part of array to another position
[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5] — copies from index 3 to start (index 0)
10. Quick Recipes — Real World Patterns
These are the combinations you will reach for most often in real projects:
const users = [
{ id: 1, name: "Randhir", age: 25, active: true, score: 92 },
{ id: 2, name: "Priya", age: 22, active: false, score: 78 },
{ id: 3, name: "Amit", age: 28, active: true, score: 85 },
{ id: 4, name: "Neha", age: 19, active: true, score: 65 },
{ id: 5, name: "Rahul", age: 30, active: false, score: 91 },
];
// Get names of all active users sorted alphabetically
const activeNames = users
.filter(u => u.active)
.sort((a, b) => a.name.localeCompare(b.name))
.map(u => u.name);
// ["Amit", "Neha", "Randhir"]
// Get average score of active users
const avgScore = users
.filter(u => u.active)
.reduce((sum, u, _, arr) => sum + u.score / arr.length, 0);
// 80.67
// Remove duplicates from array
const tags = ["js", "css", "js", "html", "css", "js"];
const unique = [...new Set(tags)];
// ["js", "css", "html"]
// Group users by active status
const grouped = users.reduce((acc, u) => {
const key = u.active ? "active" : "inactive";
acc[key] = acc[key] || [];
acc[key].push(u);
return acc;
}, {});
// { active: [...], inactive: [...] }
// Find user by ID (returns undefined if not found)
const getUser = id => users.find(u => u.id === id);
getUser(3); // { id: 3, name: "Amit", ... }
// Check if a specific user exists
const exists = users.some(u => u.name === "Priya");
// true
// Get top 3 users by score
const topThree = [...users]
.sort((a, b) => b.score - a.score)
.slice(0, 3)
.map(u => ({ name: u.name, score: u.score }));
// [{ name: "Randhir", score: 92 }, { name: "Rahul", score: 91 }, { name: "Amit", score: 85 }]
// Flatten and deduplicate tags from all users
const allUsers = [
{ name: "Randhir", tags: ["js", "php", "css"] },
{ name: "Priya", tags: ["js", "python"] },
];
const allTags = [...new Set(allUsers.flatMap(u => u.tags))];
// ["js", "php", "css", "python"]
Quick Reference — All Methods at a Glance
| Method | What It Does | Mutates? | Returns |
|---|---|---|---|
| push() | Add to end | ✅ Yes | New length |
| pop() | Remove from end | ✅ Yes | Removed element |
| unshift() | Add to beginning | ✅ Yes | New length |
| shift() | Remove from beginning | ✅ Yes | Removed element |
| splice() | Add/remove anywhere | ✅ Yes | Removed elements |
| sort() | Sort elements | ✅ Yes | Sorted array |
| reverse() | Reverse order | ✅ Yes | Reversed array |
| fill() | Fill with value | ✅ Yes | Modified array |
| map() | Transform every element | ❌ No | New array |
| filter() | Keep matching elements | ❌ No | New array |
| reduce() | Reduce to single value | ❌ No | Any value |
| find() | First matching element | ❌ No | Element or undefined |
| findIndex() | Index of first match | ❌ No | Index or -1 |
| includes() | Check if value exists | ❌ No | Boolean |
| some() | At least one matches | ❌ No | Boolean |
| every() | All elements match | ❌ No | Boolean |
| flat() | Flatten nested arrays | ❌ No | New array |
| flatMap() | Map then flatten | ❌ No | New array |
| slice() | Extract portion | ❌ No | New array |
| concat() | Merge arrays | ❌ No | New array |
| join() | Array to string | ❌ No | String |
| forEach() | Loop, no return value | ❌ No | undefined |
Common Mistakes to Avoid
1. sort() without a compare function
// ❌ Wrong — sorts numbers as strings
[10, 1, 5, 30, 2].sort()
// [1, 10, 2, 30, 5] — alphabetical order, not numerical
// ✅ Correct
[10, 1, 5, 30, 2].sort((a, b) => a - b)
// [1, 2, 5, 10, 30]
2. Mutating the original array accidentally
// ❌ sort(), reverse(), splice() all mutate the original
const original = [3, 1, 2];
const sorted = original.sort(); // original is now sorted too!
console.log(original); // [1, 2, 3] — modified!
// ✅ Spread first to avoid mutation
const sorted = [...original].sort((a, b) => a - b);
console.log(original); // [3, 1, 2] — untouched
3. Using forEach when you need a return value
// ❌ Wrong — forEach always returns undefined
const doubled = [1, 2, 3].forEach(n => n * 2);
console.log(doubled); // undefined
// ✅ Use map() when you need the result
const doubled = [1, 2, 3].map(n => n * 2);
console.log(doubled); // [2, 4, 6]
4. Chaining without understanding what each step returns
// ❌ Wrong — filter returns array, but indexOf returns number
// Cannot chain map() on a number
const result = users.filter(u => u.active).indexOf(someUser).map(...) // Error!
// ✅ Understand what each method returns before chaining
const result = users
.filter(u => u.active) // returns array
.map(u => u.name) // returns array
.sort(); // returns array
Final Thought
JavaScript array methods are one of the highest-leverage things to master
as a developer. Once you internalize map(),
filter(), and reduce() — and understand which
methods mutate the original and which return new arrays — you will write
dramatically cleaner, more expressive code with less effort.
The single most important habit: reach for map(),
filter(), and find() before you reach for a
for loop. Not because loops are wrong, but because these
methods tell the reader exactly what you are trying to do — transform,
filter, or find — without them having to read every line to figure it out.
Stuck on a specific array problem in your project? Drop us a message on our contact page — we will help you find the cleanest solution.
📚 You Might Also Like
- → How to Start Freelancing as a Web Developer in 2026 (Complete Beginner's Guide) miscellaneous
- → JavaScript Promises vs Async/Await — Complete Guide with Examples javascript
- → Laravel 12 Features You Should Know (2026 Update) Laravel
- → Array Coding Interview Problems — Two Sum, Kadane, Sliding Window & More miscellaneous
- → Interview Prep: Common Developer Interview Questions & Answers (2026 Guide) Laravel