Arrays sit at the centre of almost every JavaScript program. You fetch a list of products, hold a set of form values, store chat messages, and transform API responses before rendering them. Modern JavaScript gives you a rich set of built-in methods for working with those lists, and learning them well means you can replace long, error-prone loops with short, readable expressions. The javascript array methods in this cheat sheet are the ones working developers reach for daily: map, filter, reduce, find, some, every, sort, and a few supporting helpers.
Each method in this note follows the same pattern. You will see a small runnable snippet using realistic data, followed by a plain explanation of what each part does. Pay attention to two ideas that come up again and again. First, most of these methods do not modify the original array; they return a new array or a new value, which makes your code easier to reason about. Second, most of them accept a callback function that runs once for each element, receiving the element itself, its index, and the whole array. Once that callback idea clicks, the entire family of methods becomes predictable. If you load the data used in these examples from an API, combine them with the patterns in our Fetch API examples to build complete data pipelines.
map: Transform Every Element
The map method creates a new array by applying a function to every element of the original array. The new array always has the same length as the original. Use it whenever you need to convert data from one shape to another, such as turning product objects into display names, converting temperatures, or building a list of HTML strings.
const products = [
{ name: "Keyboard", price: 49 },
{ name: "Mouse", price: 25 },
{ name: "Monitor", price: 199 }
];
const names = products.map((product) => product.name);
console.log(names); // ["Keyboard", "Mouse", "Monitor"]
const pricesWithTax = products.map((product) => product.price * 1.2);
console.log(pricesWithTax); // [58.8, 30, 238.8]
In the first example, map walks through the products array and, for each object, returns just its name property. The arrow function receives one product at a time, and whatever it returns becomes the element at the same position in the new array. The second example does arithmetic instead, multiplying each price by 1.2 to add tax. Notice that products itself is unchanged after both calls, which is a big advantage over manually pushing into a new array inside a for loop. A common beginner mistake is using map when no return value is needed; if you only want side effects like logging, use forEach instead so readers know no new array is being built.
filter: Keep Only Matching Elements
The filter method creates a new array containing only the elements for which your callback returns true. The result can be the same length as the original, shorter, or even empty. It is the natural tool for search boxes, category filters, and removing invalid entries before saving data.
const orders = [
{ id: 1, total: 120, status: "paid" },
{ id: 2, total: 45, status: "pending" },
{ id: 3, total: 300, status: "paid" },
{ id: 4, total: 80, status: "cancelled" }
];
const paidOrders = orders.filter((order) => order.status === "paid");
console.log(paidOrders.length); // 2
const bigOrders = orders.filter((order) => order.total >= 100);
console.log(bigOrders.map((order) => order.id)); // [1, 3]
Here the callback tests each order object. In the first call, only orders whose status strictly equals the string “paid” survive. In the second call, the test is numeric, keeping orders with a total of at least 100. The final line chains map after filter, which is a very common style: first narrow the list down, then transform what remains. Chaining works because filter returns an array, and every array has map. When you filter based on text the user types, combine this with the timing controls in our debounce and throttle guide so filtering runs after typing pauses rather than on every keystroke.
reduce: Boil an Array Down to One Value
The reduce method is the most flexible and, for many learners, the most confusing. It processes an array and accumulates a single result, which can be a number, a string, an object, or even another array. Totals, averages, grouped counts, and flattened lists are all classic reduce jobs.
const cart = [
{ name: "Keyboard", price: 49, qty: 1 },
{ name: "Mouse", price: 25, qty: 2 }
];
const total = cart.reduce((sum, item) => {
return sum + item.price * item.qty;
}, 0);
console.log(total); // 99
The callback here receives two key arguments. The first, sum, is the accumulator: the running result carried from one step to the next. The second, item, is the current element. The value 0 after the callback is the starting value for the accumulator, and providing it avoids errors on empty arrays and makes the type of the result clear. On the first step, sum is 0 and the keyboard contributes 49. On the second step, sum is 49 and the mouse contributes 50, giving 99. Whatever the callback returns becomes the accumulator for the next step, so forgetting the return statement is the most common reduce bug and produces undefined very quickly.
Grouping With reduce
const tasks = [
{ title: "Write docs", status: "done" },
{ title: "Fix bug", status: "open" },
{ title: "Review PR", status: "open" }
];
const byStatus = tasks.reduce((groups, task) => {
if (!groups[task.status]) {
groups[task.status] = [];
}
groups[task.status].push(task.title);
return groups;
}, {});
console.log(byStatus);
// { done: ["Write docs"], open: ["Fix bug", "Review PR"] }
This example shows reduce building an object instead of a number. The accumulator starts as an empty object. For each task, the code checks whether a group for that status exists yet and creates an empty array if it does not. It then pushes the task title into the right group and returns the updated object. The result groups titles by status in a single pass. Grouping like this is also the conceptual cousin of SQL grouping, which we explain with database examples in our SQL GROUP BY and HAVING notes.
find and findIndex: Get the First Match
Where filter returns all matches, find returns only the first element that passes your test, or undefined if nothing matches. Its sibling findIndex returns the position of that first match, or -1 when there is no match. Use them for lookups by ID, which come up constantly when editing or deleting a single record.
const users = [
{ id: 101, name: "Aisha", role: "editor" },
{ id: 102, name: "Ravi", role: "viewer" },
{ id: 103, name: "Lena", role: "editor" }
];
const user = users.find((u) => u.id === 102);
console.log(user.name); // "Ravi"
const index = users.findIndex((u) => u.role === "admin");
console.log(index); // -1
The first lookup searches for the user whose ID equals 102 and returns the whole object, so we can read its name directly. The second lookup searches for an admin role that does not exist in this data, so findIndex returns -1. Always handle the not-found case explicitly. Code that assumes find always succeeds will throw an error the first time an ID is missing, usually at the worst possible moment. A quick guard such as if (!user) return; keeps lookups safe.
some and every: Answer Yes-or-No Questions
The some method returns true if at least one element passes the test, while every returns true only if all elements pass. Both stop early as soon as the answer is decided, which makes them efficient for validation checks on large arrays.
const scores = [72, 88, 59, 94]; const hasFail = scores.some((score) => score < 60); console.log(hasFail); // true const allPassed = scores.every((score) => score >= 60); console.log(allPassed); // false const formValues = ["Haseeb", "hello@example.com", ""]; const formComplete = formValues.every((value) => value.trim() !== ""); console.log(formComplete); // false
In the scores example, some finds the value 59, which is below 60, and returns true without needing to check the remaining values beyond that point for its answer. The every check fails for the same reason: not all scores are 60 or above. The form example shows a practical use, confirming that every field contains non-whitespace text before enabling a submit button. Watch out for one edge case that surprises people: every on an empty array returns true, because there is no element that fails the test. If an empty array should count as incomplete in your app, check the length separately.
sort and toSorted: Ordering Arrays Correctly
Sorting looks simple and hides two traps. By default, sort converts elements to strings and orders them alphabetically, which puts numbers in the wrong order, and it mutates the original array in place. For numeric and object sorting you must pass a comparison function. Newer browsers also offer toSorted, which returns a new sorted array and leaves the original untouched.
const numbers = [10, 2, 25, 1, 30];
const sortedAsc = [...numbers].sort((a, b) => a - b);
console.log(sortedAsc); // [1, 2, 10, 25, 30]
const sortedDesc = [...numbers].sort((a, b) => b - a);
console.log(sortedDesc); // [30, 25, 10, 2, 1]
const staff = [
{ name: "Lena", salary: 72000 },
{ name: "Aisha", salary: 68000 }
];
const bySalary = [...staff].sort((a, b) => b.salary - a.salary);
console.log(bySalary[0].name); // "Lena"
The comparison function receives two values, a and b. Returning a - b sorts ascending because a negative result means a should come first, while b - a reverses the order. For objects, subtract the relevant numeric property, as shown with salary. We spread the original array into a new one with [...numbers] before sorting so the source data stays in its original order for other parts of the program. For strings, use localeCompare instead of subtraction: names.sort((a, b) => a.localeCompare(b)) handles capitalisation and accented characters more sensibly. Sorting dates uses the same subtraction idea once you convert them with the techniques in our JavaScript date formatting guide.
Useful Supporting Methods: includes, slice, flat, and forEach
Four smaller methods round out daily work. includes checks whether a value exists in an array and returns a boolean, which reads far better than comparing an indexOf result to -1. slice copies a portion of an array without modifying the original, perfect for pagination. flat flattens nested arrays by one level by default, or deeper if you pass a depth. forEach runs a function for each element when you need side effects and no return value.
const tags = ["javascript", "arrays", "tutorial"];
console.log(tags.includes("arrays")); // true
const pageItems = [1, 2, 3, 4, 5, 6, 7, 8].slice(0, 3);
console.log(pageItems); // [1, 2, 3]
const nested = [1, [2, 3], [4, [5]]];
console.log(nested.flat()); // [1, 2, 3, 4, [5]]
console.log(nested.flat(2)); // [1, 2, 3, 4, 5]
tags.forEach((tag, index) => {
console.log(index, tag);
});
The slice(0, 3) call copies elements from index 0 up to but not including index 3, giving the first three items for page one of a list. The flat examples show why the depth argument matters: one level still leaves the innermost array intact, while a depth of 2 flattens fully for this data. You can also pass Infinity when you do not know the nesting depth. In forEach, the callback receives both the element and its index, which is handy for numbered rendering. Remember that you cannot break out of forEach early with break; if you need early exit, use a normal loop or some.
Chaining Methods and Staying Readable
The real power of these methods appears when you chain them into a small pipeline: filter to the records you care about, sort them into order, map them into display shape, and reduce if you need a total. Each step does one job and passes its result to the next. Keep chains readable by putting each method on its own line, using descriptive variable and parameter names, and breaking a very long chain into named intermediate variables. A chain longer than four or five steps is often clearer as two steps with a comment. Also remember performance basics: each method in a chain walks the array again, which is fine for hundreds of items but worth reconsidering for tens of thousands of records processed many times per second.
const result = orders
.filter((order) => order.status === "paid")
.sort((a, b) => b.total - a.total)
.map((order) => `#${order.id}: $${order.total}`);
console.log(result);
This pipeline starts from the orders data shape used earlier. It keeps only paid orders, sorts them from the largest total to the smallest, and formats each one as a short string. Because every step returns an array, the steps compose cleanly. Saving intermediate results like this to browser storage for a dashboard is straightforward with the JSON approach described in our localStorage notes, and writing them out as files on the server side follows the patterns covered for Python and other languages elsewhere on this site.
Conclusion
Mastering a small core of array methods will change how you write JavaScript every day. Use map to transform, filter to select, reduce to summarise, find to look up, some and every to validate, and sort with a proper comparator to order data without surprises. Prefer the non-mutating style, handle the not-found and empty-array cases, and keep chains short enough to read at a glance. Keep this cheat sheet nearby, rewrite one old loop each week using these methods, and the patterns will quickly become automatic.




3 thoughts on “JavaScript Array Methods You Will Use Every Day”