Essential Array Methods

Published by Brayan K

Beyond map and filter, JavaScript arrays ship with a toolbox of built-in methods — find, some, every, flat, sort, and the immutable toSorted — that let you search, test, flatten, and reorder data without writing loops.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose a result shape before choosing a method

Do you need one matching value, its index, a yes/no answer, or a transformed array? A method is easier to reason about when its return type matches the question. The methods here extend the basic transformation tools: map, filter & reduce owns those three callbacks in depth. This page focuses on searching, quantified tests, flattening and copying reorder operations.

const tasks = [
  { id: "a", done: true },
  { id: "b", done: false },
  { id: "c", done: false }
];
// A value, an index, any match, and all matches are distinct contracts.
console.log(tasks.find(task => !task.done).id);
console.log(tasks.findIndex(task => !task.done));
console.log(tasks.some(task => !task.done));
console.log(tasks.every(task => task.done));

// ✅ Expected output:
// b
// 1
// true
// false

find returns the first matching value or undefined. findIndex returns its index or -1. some and every return booleans and stop when their answer is known. Avoid building a whole filtered array merely to ask whether a match exists, unless you also need that array.

A missing value and an unsuccessful search can look the same

const values = [undefined, "ready"];
console.log(values.find(value => value === undefined));
console.log(values.findIndex(value => value === undefined));
console.log(values.find(value => value === "missing"));
console.log(values.findIndex(value => value === "missing"));

// ✅ Expected output:
// undefined
// 0
// undefined
// -1
const events = [
  { kind: "save", id: 1 }, { kind: "view", id: 2 }, { kind: "save", id: 3 }
];
console.log(events.findLast(event => event.kind === "save").id);
console.log(events.findLastIndex(event => event.kind === "save"));
console.log(events.map(event => event.id).join(","));

// ✅ Expected output:
// 3
// 2
// 1,2,3

findLast and findLastIndex express the last matching item without mutating the source with reverse. A returned object is the original object reference; finding it does not clone it. If a later edit should not affect the source, choose an explicit copy boundary. Deep Copy vs Shallow Copy & Data Structures owns that distinction.

const values = ["a", "b", "c"];
console.log(values.at(-1), values.at(-3), values.at(-4));
console.log(values[-1]);
values[-1] = "named property";
console.log(values[-1], values.at(-1), values.length);

// ✅ Expected output:
// c a undefined
// undefined
// named property c 3

Bracket access with -1 uses the property named "-1"; it is not a relative array position. at returns undefined when its relative index is outside the array. Neither form distinguishes every possible missing-versus-undefined case by its result alone.

Quantifiers have deliberate empty-array and callback rules

console.log([].every(() => false));
console.log([].some(() => true));
const attempts = [];
const result = [1, 2, 3, 4].some(value => { attempts.push(value); return value === 2; });
console.log(result, attempts.join(","));

// ✅ Expected output:
// true
// false
// true 1,2

Every is true for an empty collection because there is no counterexample. If a form requires at least one item and every item to pass, check length as a separate requirement. Some is false on empty input because no matching item exists. Short-circuiting also means a callback is not a reliable place to perform an effect for every element.

const values = [1, 2];
console.log(values.some(async () => false));
console.log(values.every(async () => false));
const decisions = await Promise.all(values.map(async value => value > 1));
console.log(decisions.some(Boolean), decisions.every(Boolean));

// ✅ Expected output:
// true
// true
// true false

These synchronous methods do not await a callback. Resolve asynchronous decisions deliberately, then quantify their booleans, or use an explicit async loop when sequential short-circuiting matters. Promise.all launches all mapped operations; it is not an early-stop network policy. Promise Combinators (all, race, allSettled, any) owns concurrency and failure coordination.

Sparse arrays do not behave like a list of explicit undefined values

const sparse = [, "ready"], someVisits = [], findVisits = [];
sparse.some((value, index) => { someVisits.push(index); return false; });
sparse.find((value, index) => { findVisits.push(index + ":" + String(value)); return false; });
console.log(someVisits.join(","));
console.log(findVisits.join(","));
console.log(sparse.includes(undefined), sparse.indexOf(undefined));

// ✅ Expected output:
// 1
// 0:undefined,1:ready
// true -1

A hole is an absent indexed property. Methods differ in whether they skip it or read it as undefined. Includes uses SameValueZero comparison, including a match for NaN; indexOf cannot find NaN and skips holes. Prefer dense arrays for ordinary records and validate that assumption at boundaries instead of relying on inconsistent hole behavior.

const values = [NaN, 0];
console.log(values.includes(NaN), values.indexOf(NaN));
console.log(values.includes(-0), values.indexOf(-0));

// ✅ Expected output:
// true -1
// true 1
const values = [1, 2, 3], visited = [];
values.some((value, index) => {
  visited.push(value);
  if (index === 0) { values[1] = 20; values.push(4); }
  return false;
});
console.log(visited.join(","));
console.log(values.join(","));

// ✅ Expected output:
// 1,20,3
// 1,20,3,4

The appended element lies beyond the initial length and is not visited in this run, while the changed existing entry is read later. Deleting or filling positions can produce further surprises. Avoid mutating the collection being tested unless that behavior is the purpose of the algorithm.

Flatten by a stated depth; flatMap flattens one result level

const nested = [1, [2, [3]]];
console.log(JSON.stringify(nested.flat()));
console.log(JSON.stringify(nested.flat(2)));
console.log(JSON.stringify([1, 2].flatMap(value => [value, value * 10])));
console.log(JSON.stringify([1, 2].flatMap(value => [[value]])));

// ✅ Expected output:
// [1,2,[3]]
// [1,2,3]
// [1,10,2,20]
// [[1],[2]]

flat defaults to one level. flatMap maps and flattens one array level; it does not recursively flatten every structure the callback returns. Non-array callback results are appended as single values. Flattening removes holes at the levels it visits. It does not deep-copy nested objects, validate a tree, detect cycles or replace a traversal with explicit depth limits.

const item = { label: "Draft" };
const source = [, [item, , "ready"]];
const flat = source.flat();
console.log(flat.length, flat[0] === item, flat[1]);
flat[0].label = "Changed";
console.log(item.label);

// ✅ Expected output:
// 2 true ready
// Changed

New array results can still share nested objects

const values = [10, 2, 1];
console.log(values.toSorted().join(","));
console.log(values.toSorted((a, b) => a - b).join(","));
console.log(values.join(","));
const rows = [{ id: "a", score: 2 }, { id: "b", score: 2 }, { id: "c", score: 3 }];
console.log(rows.toSorted((a, b) => b.score - a.score).map(row => row.id).join(","));

// ✅ Expected output:
// 1,10,2
// 1,2,10
// 10,2,1
// c,a,b

The default sort order compares string forms; it is not numeric order. A comparator returns a negative, zero or positive number. For equal comparisons, stable sorting preserves the original relative order. Returning a boolean comparator breaks the intended ordering contract. Keep the comparator pure and consistent; do not rely on an exact number of comparator calls.

const item = { n: 1 }, source = [item, { n: 2 }];
const result = source.toReversed();
console.log(result.map(x => x.n).join(","), source.map(x => x.n).join(","));
console.log(result === source, result[1] === item);
result[1].n = 9;
console.log(source[0].n);

// ✅ Expected output:
// 2,1 1,2
// false true
// 9
const source = ["a", "b", "c"];
console.log(source.with(-1, "z").join(","));
console.log(source.toSpliced(1, 1, "x", "y").join(","));
console.log(source.toSpliced(1).join(","));
console.log(source.toSpliced(1, undefined, "x").join(","));
console.log(source.join(","));

// ✅ Expected output:
// a,b,z
// a,x,y,c
// a
// a,x,b,c
// a,b,c
["a", "b"].with(2, "c");

// ✅ Expected error:
// RangeError: Invalid index : 2

An omitted toSpliced delete count removes the rest; explicitly passing undefined converts that count to zero. with replaces an existing relative index and throws outside the range. These copying methods also create dense arrays rather than preserving holes in the same way as every older method. Check support for the environments your project targets; this lesson verifies the tested Node and browser versions, not every historical engine.

Guided exercise: ask, copy and preserve

Fill the literal hints to find the last unfinished task, check whether any task is done and sort a copy numerically. The original input order remains visible so accidental mutation is easy to notice.

const tasks = [{ id: "a", done: false }, { id: "b", done: true }, { id: "c", done: false }];
console.log(tasks.___(task => !task.done).id); // 👉 replace ___ with findLast
console.log(tasks.___(task => task.done)); // 👉 replace ___ with some
const values = [3, 1, 2];
console.log(values.___((a, b) => a - b).join(",")); // 👉 replace ___ with toSorted
console.log(values.join(","));

// ✅ Expected output:
// c
// true
// 1,2,3
// 3,1,2

Brief: rank a bounded list without changing its source

Implement rankCandidates(rows, minimum, limit). Accept a dense array of at most 100 ordinary records. Every record has a unique lowercase ASCII id starting with a letter and containing at most 16 letters/digits/hyphens, a finite score from 0 through 100, and a boolean active field. Reject invalid rows even if a later filter would exclude them. Minimum is finite in 0..100; limit is an integer in 0..100. Do not coerce values.

Select active rows at or above minimum, sort by descending score with input order as the tie-breaker, take at most limit, and return fresh records containing only id and score. Preserve the input array and its records. A zero limit returns an empty result after validation. Do not add asynchronous predicates, locale-dependent ordering or deep cloning of arbitrary data.

function rankCandidates(rows, minimum, limit) {
  if (!Array.isArray(rows) || rows.length > 100) throw new TypeError("rows must be an array of at most 100");
  if (!Number.isFinite(minimum) || minimum < 0 || minimum > 100 ||
      !Number.isInteger(limit) || limit < 0 || limit > 100)
    throw new RangeError("invalid selection limits");
  const ids = new Set(), selected = [];
  for (let index = 0; index < rows.length; index++) {
    if (!Object.hasOwn(rows, index)) throw new TypeError("rows must be dense");
    const row = rows[index];
    if (row === null || typeof row !== "object" || Array.isArray(row) ||
        typeof row.id !== "string" || !/^[a-z][a-z0-9-]{0,15}$/.test(row.id) ||
        ids.has(row.id) || !Number.isFinite(row.score) || row.score < 0 || row.score > 100 ||
        typeof row.active !== "boolean")
      throw new TypeError("invalid candidate");
    ids.add(row.id);
    selected.push({ id: row.id, score: row.score, active: row.active });
  }
  return selected.filter(row => row.active && row.score >= minimum)
    .toSorted((a, b) => b.score - a.score)
    .slice(0, limit)
    .map(({ id, score }) => ({ id, score }));
}
const rows = [
  { id: "a", score: 80, active: true, secret: "omit" },
  { id: "b", score: 90, active: true },
  { id: "c", score: 90, active: true },
  { id: "d", score: 100, active: false }
];
const before = JSON.stringify(rows);
const result = rankCandidates(rows, 80, 2);
console.log(JSON.stringify(result));
console.log(JSON.stringify(rows) === before, result[0] === rows[1]);
console.log(rankCandidates(rows, 80, 0).length);
try { rankCandidates([{ id: "a", score: 120, active: false }], 0, 0); }
catch (error) { console.log(error.name, error.message); }

// ✅ Expected output:
// [{"id":"b","score":90},{"id":"c","score":90}]
// true false
// 0
// TypeError invalid candidate

The validation rule belongs to this brief, not to toSorted or filter. Those methods do not enforce a schema. Advanced Array & Object Transformations owns broader aggregation and data-shaping workflows; this page owns the particular search, quantifier and copying-method contracts.

Practice quiz

What does this complete program print? console.log([].every(()=>false),[].some(()=>true));

  • true false
  • false false
  • true true
  • false true

Answer: true false. Empty every has no counterexample; empty some has no match.

What does this complete program print? const x=[undefined];console.log(x.findIndex(v=>v===undefined),x.findIndex(v=>v===3));

  • undefined undefined
  • 0 -1
  • -1 0
  • 0 0

Answer: 0 -1. An index distinguishes a matching undefined from no match.

What does this complete program print? console.log([NaN].includes(NaN),[NaN].indexOf(NaN));

  • false -1
  • true 0
  • true -1
  • false 0

Answer: true -1. Includes matches NaN with SameValueZero; indexOf does not.

What does this complete program print? const x=[3,1,2];console.log(x.toSorted((a,b)=>a-b).join(""),x.join(""));

  • 123 123
  • 312 123
  • 321 312
  • 123 312

Answer: 123 312. The copying sort leaves source order unchanged.

What does this complete program print? console.log(JSON.stringify([1,2].flatMap(x=>[[x]])));

  • [[1],[2]]
  • [1,2]
  • [[[1]],[[2]]]
  • [1,1,2,2]

Answer: [[1],[2]]. flatMap removes exactly one array level from callback results.

What does this complete program print? console.log([1,2].some(async()=>false));

  • false
  • true
  • undefined
  • Promise

Answer: true. A promise object is truthy; some does not await it.

What does this complete program print? const x=["a","b"];console.log(x.at(-1),x[-1]);

  • a undefined
  • b b
  • b undefined
  • undefined b

Answer: b undefined. at uses a relative index; brackets read a named property.

What does this complete program print? console.log(["a","b","c"].toSpliced(1,undefined,"x").join(""));

  • ax
  • abc
  • a
  • axbc

Answer: axbc. An explicit undefined delete count means zero deletions.

Continue this course

Related lessons