Tool Blog JS Array Methods
← All Articles
🗂️

JavaScript Array Methods 2026 — Complete Guide With Real Examples

Arrays are how JavaScript stores lists of data — a list of products, a list of users, a list of search results. And array methods are the tools that let you work with that data elegantly. Knowing these methods well is what separates developers who write ten lines of clean code from those who write fifty lines of messy loops. This guide covers every important array method with real, practical examples you can use immediately.

✍️ By UTS Sites 📅 Updated: January 2026 ⏱️ 16 min read 🎯 Beginner to Intermediate
💡

Every example in this guide runs in your browser console right now. Press F12 → click Console → paste any code → press Enter. Or test it in our free HTML Editor Online Pro inside a <script> tag.

📖

What is a JavaScript Array — and Why Do Methods Matter?

An array is an ordered list of values stored in a single variable. Think of it as a numbered container — you can put strings, numbers, objects, or even other arrays inside it, and access each item by its position (called an index, starting at 0).

Arrays — The Basics First // Creating arrays const fruits = ["mango", "apple", "banana", "orange"]; const numbers = [10, 25, 8, 42, 3]; const users = [ { name: "Arjun", age: 25, active: true }, { name: "Priya", age: 28, active: false }, { name: "Rahul", age: 22, active: true } ]; // Accessing items by index (starts at 0) console.log(fruits[0]); // "mango" console.log(fruits[2]); // "banana" console.log(fruits.length); // 4 — number of items // Last item — works for any array length console.log(fruits[fruits.length - 1]); // "orange" console.log(fruits.at(-1)); // "orange" — modern way (2026)

Array methods are built-in functions that let you manipulate, transform, and query arrays without writing manual loops every time. They make your code shorter, more readable, and much easier to reason about. In 2026, these methods — especially map, filter, and reduce — are considered fundamental JavaScript knowledge that every developer must know.

🎯

Mutating vs Non-Mutating: Some array methods change (mutate) the original array. Others return a new array and leave the original untouched. Knowing which is which prevents many subtle bugs. We'll mark each method clearly throughout this guide.

🔄

forEach — Loop Through Every Item

forEach is the simplest array method. It calls a function once for every item in the array. That's it. It doesn't return anything — it's purely for side effects like logging, updating the DOM, or triggering actions. Think of it as a clean replacement for a for loop.

.forEach() Does NOT mutate Returns: undefined
Calls a callback function once for each array item. Use it when you want to do something with each item but don't need to create a new array.
const products = [ { name: "HTML Editor", price: 0 }, { name: "CSS Toolkit", price: 499 }, { name: "JS Library", price: 999 } ]; // Log each product products.forEach(function(product) { console.log(`${product.name}: ₹${product.price}`); }); // Arrow function version — cleaner products.forEach(product => { console.log(`${product.name}: ₹${product.price}`); }); // With index parameter fruits.forEach((fruit, index) => { console.log(`${index + 1}. ${fruit}`); }); // 1. mango 2. apple 3. banana 4. orange
🗺️

map — Transform Every Item Into Something New

map is one of the most used array methods in all of JavaScript. It takes every item in an array, transforms it with a function, and returns a brand new array of the same length with the transformed values. The original array is never touched.

The mental model that makes map click: imagine a factory assembly line. Items go in one end, get transformed at each station, and come out the other end as something new. The input array and the output array always have the same number of items.

.map() Does NOT mutate Returns: new array (same length)
Transforms every item and returns a new array of the same length. Use it whenever you want to convert data from one format to another.
const numbers = [1, 2, 3, 4, 5]; // Double every number const doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6, 8, 10] console.log(numbers); // [1, 2, 3, 4, 5] — unchanged // Extract one property from an array of objects const users = [ { name: "Arjun", age: 25 }, { name: "Priya", age: 28 }, { name: "Rahul", age: 22 } ]; const names = users.map(user => user.name); console.log(names); // ["Arjun", "Priya", "Rahul"] // Add a new property to each object const withGreeting = users.map(user => ({ ...user, greeting: `Hello, ${user.name}!` })); // Format prices for display const prices = [499, 999, 1499]; const formatted = prices.map(p => `₹${p.toLocaleString()}`); console.log(formatted); // ["₹499", "₹999", "₹1,499"]
💡

map vs forEach: Use map when you want to create a new array of transformed values. Use forEach when you want to do something with each item but don't need the result as a new array. If you find yourself building an array manually inside a forEach, switch to map.

🔍

filter — Keep Only the Items You Want

filter creates a new array containing only the items that pass a test you define. For each item, your function returns true (keep it) or false (skip it). The resulting array can be shorter than the original — or even empty if nothing passes the test.

.filter() Does NOT mutate Returns: new array (same or shorter)
Returns a new array with only the items where the callback returns true. Perfect for searching, hiding/showing data, and removing unwanted items.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8]; // Keep only even numbers const evens = numbers.filter(n => n % 2 === 0); console.log(evens); // [2, 4, 6, 8] // Filter objects by condition const users = [ { name: "Arjun", age: 25, active: true }, { name: "Priya", age: 17, active: true }, { name: "Rahul", age: 32, active: false }, { name: "Meera", age: 28, active: true } ]; // Only active users const activeUsers = users.filter(user => user.active); // Adults only (18+) const adults = users.filter(user => user.age >= 18); // Search — filter by name containing a string const searchQuery = "ar"; const results = users.filter(user => user.name.toLowerCase().includes(searchQuery.toLowerCase()) ); console.log(results.map(u => u.name)); // ["Arjun"] // Remove duplicates with filter const dupes = [1, 2, 2, 3, 3, 4]; const unique = dupes.filter((val, index, arr) => arr.indexOf(val) === index); console.log(unique); // [1, 2, 3, 4]

reduce — Boil an Array Down to a Single Value

reduce is the most powerful and most misunderstood array method. It processes each item in the array and accumulates a single result — a sum, an object, a string, another array. Once you truly understand reduce, you realize you can use it to build almost anything.

The function you pass to reduce receives two key arguments: the accumulator (the running result so far) and the current item (the element being processed). Whatever you return from the function becomes the new accumulator for the next iteration.

.reduce() Does NOT mutate Returns: single value (any type)
Reduces the array to a single value by running a callback on each item with an accumulator. The most versatile array method — can replicate map, filter, and more.
// Sum all numbers const numbers = [10, 25, 8, 42, 15]; const total = numbers.reduce((sum, current) => sum + current, 0); console.log(total); // 100 // ↑ This 0 is the initial value of "sum" // Calculate total cart price const cart = [ { name: "HTML Course", price: 999, qty: 1 }, { name: "CSS Course", price: 799, qty: 2 }, { name: "JS Course", price: 1299, qty: 1 } ]; const cartTotal = cart.reduce((total, item) => { return total + (item.price * item.qty); }, 0); console.log(cartTotal); // 3896 // Group items by a category — reduce to an object const people = [ { name: "Arjun", dept: "Engineering" }, { name: "Priya", dept: "Design" }, { name: "Rahul", dept: "Engineering" }, { name: "Meera", dept: "Design" } ]; const byDept = people.reduce((groups, person) => { const dept = person.dept; if (!groups[dept]) groups[dept] = []; groups[dept].push(person.name); return groups; }, {}); console.log(byDept); // { Engineering: ["Arjun", "Rahul"], Design: ["Priya", "Meera"] }
⚠️

Always provide an initial value as the second argument to reduce. Without it, reduce uses the first array item as the initial accumulator — which works for numbers but causes silent bugs with objects and strings. Make it a habit: always pass the initial value.

🔎

find, findIndex, some, every — Searching Arrays

Sometimes you don't want to transform or filter an array — you just want to find something in it, or check if something exists. These four methods handle exactly that, each returning a different type of result.

.find() Does NOT mutate Returns: first matching item or undefined
Returns the first item where the callback returns true. Stops as soon as it finds a match — efficient for large arrays.
const users = [ { id: 1, name: "Arjun", role: "admin" }, { id: 2, name: "Priya", role: "user" }, { id: 3, name: "Rahul", role: "user" } ]; // Find by ID const user = users.find(u => u.id === 2); console.log(user); // { id: 2, name: "Priya", role: "user" } // Find admin const admin = users.find(u => u.role === "admin"); console.log(admin.name); // "Arjun" // If nothing found — returns undefined const notFound = users.find(u => u.id === 99); console.log(notFound); // undefined
.findIndex() Does NOT mutate Returns: index number or -1
Like find() but returns the index position instead of the item itself. Returns -1 if not found.
const idx = users.findIndex(u => u.id === 2); console.log(idx); // 1 // Practical use: update an item in an array const index = users.findIndex(u => u.id === 2); if (index !== -1) { users[index].role = "admin"; // update Priya to admin }
.some() and .every() Does NOT mutate Returns: boolean (true/false)
some() returns true if at least one item passes the test. every() returns true only if ALL items pass the test. Both stop early once the result is determined.
const scores = [72, 88, 45, 91, 63]; // some — does ANY score pass? (at least one) const anyPassed = scores.some(score => score >= 90); console.log(anyPassed); // true (91 passes) // every — do ALL scores pass? const allPassed = scores.every(score => score >= 50); console.log(allPassed); // false (45 fails) // Real use: check if form fields are all filled const fields = ["name", "email", "message"]; const formData = { name: "Arjun", email: "[email protected]", message: "" }; const isComplete = fields.every(field => formData[field].trim() !== ""); console.log(isComplete); // false (message is empty)
🔢

sort and reverse — Ordering Arrays

sort reorders the items in an array. reverse flips the order. Both of these methods are important — and both have a gotcha that catches almost every beginner at least once.

.sort() ⚠️ MUTATES original Returns: same array (sorted)
Sorts items in place. Without a comparison function, it converts everything to strings first — which breaks number sorting in unexpected ways. Always pass a compare function for numbers and objects.
// ❌ WRONG for numbers — sorts as strings! const nums = [10, 2, 100, 25]; nums.sort(); console.log(nums); // [10, 100, 2, 25] — wrong! (string order) // ✅ CORRECT — use compare function for numbers const nums2 = [10, 2, 100, 25]; nums2.sort((a, b) => a - b); // ascending console.log(nums2); // [2, 10, 25, 100] nums2.sort((a, b) => b - a); // descending console.log(nums2); // [100, 25, 10, 2] // Sort strings alphabetically const names = ["Rahul", "Arjun", "Priya"]; names.sort((a, b) => a.localeCompare(b)); console.log(names); // ["Arjun", "Priya", "Rahul"] // Sort objects by a property const products = [ { name: "B Product", price: 500 }, { name: "A Product", price: 200 }, { name: "C Product", price: 800 } ]; // Sort by price (low to high) products.sort((a, b) => a.price - b.price); // Sort by name alphabetically products.sort((a, b) => a.name.localeCompare(b.name)); // Sort without mutating original — use spread first const sorted = [...products].sort((a, b) => a.price - b.price);
⚠️

sort() mutates the original array. If you want to sort without changing the original, make a copy first: const sorted = [...originalArray].sort(...). The spread operator [...arr] creates a shallow copy, so sort operates on the copy instead of the original.

🔧

push, pop, shift, unshift, splice — Modifying Arrays

These are the classic methods for adding and removing items from arrays. They all mutate the original array — which is sometimes exactly what you want.

Add and Remove Methods const arr = ["b", "c", "d"]; // push — add to END (returns new length) arr.push("e"); console.log(arr); // ["b", "c", "d", "e"] // pop — remove from END (returns removed item) const last = arr.pop(); console.log(last); // "e" console.log(arr); // ["b", "c", "d"] // unshift — add to BEGINNING (returns new length) arr.unshift("a"); console.log(arr); // ["a", "b", "c", "d"] // shift — remove from BEGINNING (returns removed item) const first = arr.shift(); console.log(first); // "a" console.log(arr); // ["b", "c", "d"] // splice — add, remove, or replace at any position // splice(startIndex, deleteCount, ...itemsToAdd) arr.splice(1, 0, "NEW"); // insert at index 1 console.log(arr); // ["b", "NEW", "c", "d"] arr.splice(1, 1); // remove 1 item at index 1 console.log(arr); // ["b", "c", "d"] arr.splice(1, 1, "REPLACED"); // replace item at index 1 console.log(arr); // ["b", "REPLACED", "d"]
✂️

slice, concat, flat, includes — Essential Utilities

These four methods handle slicing arrays, combining them, flattening nested arrays, and checking if a value exists. You'll reach for all of them regularly in real projects.

slice, concat, flat, includes // slice — extract a portion WITHOUT mutating // slice(startIndex, endIndex) — endIndex NOT included const fruits = ["mango", "apple", "banana", "orange", "grape"]; const middle = fruits.slice(1, 4); console.log(middle); // ["apple", "banana", "orange"] console.log(fruits); // unchanged // Negative index counts from end const last2 = fruits.slice(-2); console.log(last2); // ["orange", "grape"] // concat — merge two or more arrays const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const merged = arr1.concat(arr2); console.log(merged); // [1, 2, 3, 4, 5, 6] // Modern alternative — spread operator const merged2 = [...arr1, ...arr2]; // includes — check if a value exists const roles = ["admin", "editor", "viewer"]; console.log(roles.includes("admin")); // true console.log(roles.includes("superuser")); // false // flat — flatten nested arrays const nested = [1, [2, 3], [4, [5, 6]]]; console.log(nested.flat()); // [1, 2, 3, 4, [5, 6]] — 1 level console.log(nested.flat(2)); // [1, 2, 3, 4, 5, 6] — 2 levels console.log(nested.flat(Infinity));// flatten ALL levels // flatMap — map then flatten (very useful) const sentences = ["hello world", "good morning"]; const words = sentences.flatMap(s => s.split(" ")); console.log(words); // ["hello", "world", "good", "morning"]
📋

Complete Array Methods Cheatsheet — Quick Reference

Bookmark this table. Every important JavaScript array method in one place.

MethodReturnsMutates?One-line description
forEach(fn)undefinedNoRun a function on each item
map(fn)new arrayNoTransform each item → new array same length
filter(fn)new arrayNoKeep only items where fn returns true
reduce(fn, init)any valueNoAccumulate items into a single result
find(fn)item or undefinedNoFirst item where fn returns true
findIndex(fn)number (-1)NoIndex of first match, or -1
some(fn)booleanNoTrue if at least one item passes
every(fn)booleanNoTrue only if ALL items pass
includes(val)booleanNoTrue if val exists in array
indexOf(val)number (-1)NoIndex of first occurrence of val
sort(fn)same array⚠️ YESSort items in place
reverse()same array⚠️ YESReverse order in place
push(...items)new length⚠️ YESAdd items to end
pop()removed item⚠️ YESRemove last item
shift()removed item⚠️ YESRemove first item
unshift(...items)new length⚠️ YESAdd items to beginning
splice(i,d,...add)removed items⚠️ YESAdd/remove/replace at any position
slice(start,end)new arrayNoCopy a portion of the array
concat(...arrays)new arrayNoMerge arrays together
flat(depth)new arrayNoFlatten nested arrays
flatMap(fn)new arrayNomap() then flat(1)
join(separator)stringNoConvert array to a string
Array.from()new arrayNoCreate array from any iterable
Array.isArray()booleanNoCheck if something is an array
scroll

Practice Array Methods in Your Browser — Free

Open HTML Editor Online Pro, write a script tag with your array code, and run it instantly. Experiment freely — change the data, chain methods together, break things and fix them. That's how JavaScript actually gets learned.

⚡ Open Free HTML Editor →

Frequently Asked Questions About JavaScript Array Methods

Q: What is the difference between map and forEach?
Both iterate through every item in an array. The difference is what they return. map returns a new array of the same length with the transformed values — use it when you want a new array. forEach returns nothing (undefined) — use it when you want to perform an action on each item but don't need the result as a new array. If you're building a new array inside a forEach, that's usually a sign you should be using map.

Q: When should I use filter vs find?
Use filter when you want all items that match a condition — it always returns an array (which may be empty). Use find when you want just the first match — it returns the item itself (or undefined). If you're looking up a specific record by ID, find is the right choice. If you're filtering a list to show active items, filter is right.

Q: Is reduce hard to understand?
It takes a bit more time to understand than map and filter, but once it clicks, it becomes one of your most-used tools. The mental model: imagine reduce walking through the array item by item, carrying a "running total" (the accumulator). At each step, it updates the total based on the current item. When it reaches the end, it returns the final total. That "total" can be a number, string, object, or another array.

Q: Why does sort() behave strangely with numbers?
By default, sort() converts items to strings and sorts them lexicographically (like a dictionary). That means 10 comes before 2 because "1" comes before "2" alphabetically. Always pass a comparison function when sorting numbers: array.sort((a, b) => a - b). The function returns negative if a should come first, positive if b should come first, and 0 if equal.

Q: Can I chain array methods together?
Yes — and this is one of the most powerful patterns in JavaScript. Since methods like map and filter return new arrays, you can chain them: users.filter(u => u.active).map(u => u.name).sort(). Just be mindful of performance with very large arrays — each chained method creates a new array and iterates through it. For very large datasets, a single reduce may be more efficient than multiple chained methods.