October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

JavaScript Arrays: Which Method Should You Use for Each Task?

A practical guide to JavaScript arrays: choose methods by what they return, transform or find values, accumulate results, sort safely, and read from the end.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use map() to transform every item, filter() to keep all matches, find() to get the first match, includes() to check membership, and reduce() to accumulate one result. For sorting, choose between sort(), which changes the original array, and toSorted(), which returns a sorted copy. The right choice depends on what you need back and whether the original data may change.

How do JavaScript arrays work?

An array is an indexed, resizable collection. Its items are addressed by positions beginning at zero, and its length property reports the array’s length. JavaScript does not require every item to have the same type, though keeping related data consistent usually makes code easier to understand. See MDN’s guide to indexed collections and Array reference.

As an Amazon Associate I earn from qualifying purchases.

const values = [12, "hello", true];
console.log(values[0]); // 12
console.log(values.length); // 3

Most array callbacks receive the current element, its index, and the array being processed. The callback’s return value has different meaning for different methods: it becomes a mapped value, a test result, or the next accumulator state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which array method fits the task?

What you need Method What it returns Effect on the original
Transform each populated item map() A new array with callback results Does not change the array by itself
Keep every item that passes a test filter() A new shallow array Does not change the array by itself
Get the first item that passes a test find() The item, or undefined Does not change the array by itself
Check whether a value is present includes() true or false Does not change the array
Combine items into one result reduce() The final accumulator value Does not change the array by itself
Sort the existing array sort() The same array, sorted Mutates the array
Sort while preserving the original toSorted() A new sorted array Leaves the original unchanged
Read an item relative to the end at(-1) The item, or undefined Does not change the array

How do I transform every item with map()?

Use map() when each visited item should produce a corresponding output. It calls the callback for each populated slot and returns a new array of callback results; it does not edit the source array unless the callback itself changes something.

const prices = [12, 25, 8];
const withTax = prices.map((price) => price * 1.1);

console.log(withTax); // [13.2, 27.500000000000004, 8.8]
console.log(prices);  // [12, 25, 8]

Use the returned array. If you only want to perform an action for each item and do not need a new array, choose forEach() or a loop instead. See MDN’s map() reference.

When should I use filter() instead of find()?

Use filter() to keep all matches

filter() returns a new shallow array containing every item whose callback returns a truthy result. It can return an empty array, one item, or many.

const prices = [12, 25, 8];
const affordable = prices.filter((price) => price < 20);

console.log(affordable); // [12, 8]

Use find() to get the first match

find() returns the first item whose callback passes the test, then stops searching. If no item matches, the result is undefined.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const firstAffordable = prices.find((price) => price < 20);
console.log(firstAffordable); // 12

These methods answer different questions: “Which items match?” calls for filter(); “What is the first matching item?” calls for find(). MDN documents their behavior in its filter() reference and find() reference.

How do I check whether an array includes a value?

Use includes() for a direct yes-or-no check. It returns a boolean rather than the matching item or a filtered array.

const hasEight = prices.includes(8);
console.log(hasEight); // true

For an object or a condition-based search, use find() or some() as appropriate; includes() checks for the specified value itself. See MDN’s includes() reference.

When should I use reduce()?

Choose reduce() when the items should be combined into one accumulated result, such as a sum. The reducer returns the next accumulator value, which is passed to the callback on the next iteration. An explicit initial value makes the starting state clear and allows the operation to work on an empty array.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 45

Without an initial value, reduce() starts with the first present element as its accumulator. Calling it on an empty array without an initial value throws an error. For a sum, pass 0; for another operation, choose an initial value that matches the type and meaning of the result. More details are in MDN’s reduce() reference.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I sort numbers without changing the original array?

sort() rearranges the original array in place. Its default order compares string representations, not numeric values, so provide a comparator for numeric sorting. The comparator (a, b) => a - b sorts numbers in ascending order.

const prices = [12, 25, 8];
const sortedCopy = prices.toSorted((a, b) => a - b);

console.log(sortedCopy); // [8, 12, 25]
console.log(prices);     // [12, 25, 8]

If you want to change the existing array, use prices.sort((a, b) => a - b). If the original order must remain available, use toSorted() instead. MDN explains in-place sorting in its sort() reference and the copying alternative in its toSorted() reference.

How do I get the last item in an array?

Use at(-1) to address the final item relative to the end. If the array is empty, it returns undefined.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const lastPrice = prices.at(-1);
console.log(lastPrice); // 8

prices[-1] is not negative indexing in JavaScript; it accesses a property named -1. The at() method is widely available in current runtimes, but check support if your code must run in an older environment. See MDN’s at() reference.

What should I know about sparse arrays?

A sparse array has empty slots, which are different from slots that explicitly contain undefined. Methods do not all handle empty slots the same way: map(), filter(), and forEach() skip holes, while find() and includes() treat holes as undefined during traversal. Do not assume these methods are interchangeable when an array may contain holes. MDN covers this behavior in its Array reference and find() reference.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.