Array functions
Each method below is something you will reach for while solving array problems. Skim the short description, then copy the snippets for common situations.
Prefer Overview for how arrays work, and Problems for practice once problems are linked.
Creating & copying
Ways to make a new array or copy one you already have.
Array()
Makes a new empty array, or one with a given length.
// ——— empty ———
const a: number[] = [];
const b = new Array<number>();
// ——— fixed length (empty slots) ———
const slots = new Array(5); // length 5, no values yet
// ——— length then fill ———
const zeros = new Array(5).fill(0); // [0, 0, 0, 0, 0]Array.from()
Builds an array from a length, a string, or another list-like value.
// ——— from a length + index ———
const idx = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
// ——— from a string ———
const chars = Array.from('hi'); // ['h', 'i']
// ——— from a Set (unique values → array) ———
const unique = Array.from(new Set([1, 1, 2])); // [1, 2]
// ——— map while building ———
const doubled = Array.from([1, 2, 3], (v) => v * 2); // [2, 4, 6]Array.of()
Makes an array from the arguments you pass in.
// ——— values as arguments ———
const a = Array.of(1, 2, 3); // [1, 2, 3]
// ——— single number stays a value (unlike new Array(3)) ———
const one = Array.of(3); // [3]
const emptySlots = new Array(3); // length 3, emptyfill()
Puts the same value into every slot (or a range of slots).
// ——— fill everything ———
const a = new Array(4).fill(0); // [0, 0, 0, 0]
// ——— fill a range [start, end) ———
const b = [1, 2, 3, 4, 5];
b.fill(9, 1, 4); // [1, 9, 9, 9, 5]
// ——— reset before a run ———
const dp = new Array(n).fill(Infinity);slice()
Copies part of the array into a new array. Leaves the original alone.
const a = [10, 20, 30, 40, 50];
// ——— full shallow copy ———
const copy = a.slice();
// ——— from index to end ———
const tail = a.slice(2); // [30, 40, 50]
// ——— range [start, end) ———
const mid = a.slice(1, 4); // [20, 30, 40]
// ——— last k items ———
const last2 = a.slice(-2); // [40, 50]concat()
Joins arrays together and returns a new one.
const left = [1, 2];
const right = [3, 4];
// ——— join two arrays ———
const all = left.concat(right); // [1, 2, 3, 4]
// ——— rotate left by k using slice + concat ———
const k = 2;
const a = [1, 2, 3, 4, 5];
const rotL = a.slice(k).concat(a.slice(0, k)); // [3, 4, 5, 1, 2]structuredClone()
Deep-copies a value — useful when the array holds nested objects or other arrays.
// ——— nested array copy ———
const grid = [[1, 2], [3, 4]];
const copy = structuredClone(grid);
copy[0][0] = 9;
// grid is still [[1, 2], [3, 4]]
// ——— array of objects ———
const rows = [{ id: 1 }, { id: 2 }];
const cloned = structuredClone(rows);Reading & size
Look at one box, or check whether something really is an array.
at()
Reads one value by index. Negative indexes count from the end.
const a = [10, 20, 30, 40];
// ——— from the front ———
const first = a.at(0); // 10
const third = a.at(2); // 30
// ——— from the end ———
const last = a.at(-1); // 40
const secondLast = a.at(-2); // 30Array.isArray()
Tells you whether a value is an array.
// ——— guard before treating as array ———
function len(value: unknown): number {
return Array.isArray(value) ? value.length : 0;
}
Array.isArray([1, 2]); // true
Array.isArray('hi'); // false
Array.isArray({ length: 2 }); // falseAdding & removing
Grow or shrink the row from the ends, or change the middle.
push()
Adds one or more values at the end.
const a = [1, 2, 3];
// ——— add one ———
a.push(4); // [1, 2, 3, 4]
// ——— add several ———
a.push(5, 6); // [1, 2, 3, 4, 5, 6]
// ——— build a result list ———
const out: number[] = [];
for (const v of nums) {
if (v > 0) out.push(v);
}pop()
Removes and returns the last value.
const stack = [1, 2, 3];
// ——— remove last ———
const top = stack.pop(); // 3; stack is [1, 2]
// ——— undo / stack pattern ———
while (stack.length > 0) {
const v = stack.pop()!;
// use v
}unshift()
Adds one or more values at the front — everything else slides right.
const a = [2, 3];
// ——— add at front ———
a.unshift(1); // [1, 2, 3]
// ——— note: slower than push on big arrays (everyone slides) ———
a.unshift(0, -1); // [-1, 0, 1, 2, 3]shift()
Removes and returns the first value — everything else slides left.
const queue = [10, 20, 30];
// ——— take from front ———
const next = queue.shift(); // 10; queue is [20, 30]
// ——— simple queue (prefer index pointer on hot paths) ———
while (queue.length > 0) {
const v = queue.shift()!;
// use v
}splice()
Inserts, removes, or replaces values at any index.
const a = [1, 2, 3, 4, 5];
// ——— remove 1 at index 2 ———
a.splice(2, 1); // [1, 2, 4, 5]
// ——— insert at index 1 ———
a.splice(1, 0, 99); // [1, 99, 2, 4, 5]
// ——— replace 2 items starting at index 2 ———
a.splice(2, 2, 7, 8); // [1, 99, 7, 8, 5]copyWithin()
Copies a stretch of values to another place inside the same array.
const a = [1, 2, 3, 4, 5];
// ——— copy [0, 3) onto index 2 ———
a.copyWithin(2, 0, 3); // [1, 2, 1, 2, 3]
// ——— slide a prefix over a suffix ———
const b = [10, 20, 30, 40, 50];
b.copyWithin(0, 2); // [30, 40, 50, 40, 50]Searching
Find a value, its place, or whether anything matches a rule.
indexOf()
Returns the first index of a value, or -1 if it is missing.
const a = [7, 3, 9, 3];
// ——— first match ———
const i = a.indexOf(3); // 1
const missing = a.indexOf(5); // -1
// ——— start searching later ———
const next = a.indexOf(3, 2); // 3lastIndexOf()
Same as indexOf(), but searches from the end.
const a = [7, 3, 9, 3];
// ——— last match ———
const i = a.lastIndexOf(3); // 3
// ——— search backward before an index ———
const earlier = a.lastIndexOf(3, 2); // 1includes()
Returns true if the value is in the array.
const a = [1, 2, 3];
// ——— membership check ———
if (a.includes(2)) {
// found
}
// ——— with a Set is faster for many lookups ———
const seen = new Set(a);
seen.has(2); // truefind()
Returns the first value that matches a test function.
const a = [1, 4, 6, 9];
// ——— first even ———
const even = a.find((v) => v % 2 === 0); // 4
// ——— first object match ———
const users = [{ id: 1 }, { id: 2 }];
const user = users.find((u) => u.id === 2);findIndex()
Returns the index of the first value that matches a test function.
const a = [1, 4, 6, 9];
// ——— index of first even ———
const i = a.findIndex((v) => v % 2 === 0); // 1
// ——— none match ———
const none = a.findIndex((v) => v < 0); // -1findLast()
Like find(), but starts from the end.
const a = [1, 4, 6, 9];
// ——— last even ———
const even = a.findLast((v) => v % 2 === 0); // 6findLastIndex()
Like findIndex(), but starts from the end.
const a = [1, 4, 6, 9];
// ——— index of last even ———
const i = a.findLastIndex((v) => v % 2 === 0); // 2some()
Returns true if at least one value matches a test.
const a = [1, 3, 5, 8];
// ——— any even? ———
const hasEven = a.some((v) => v % 2 === 0); // true
// ——— any negative? ———
const hasNeg = a.some((v) => v < 0); // falseevery()
Returns true only if every value matches a test.
const a = [2, 4, 6];
// ——— all even? ———
const allEven = a.every((v) => v % 2 === 0); // true
// ——— compare two arrays of equal length ———
const same =
a.length === b.length && a.every((v, i) => v === b[i]);Sorting & reordering
Put values in order, flip the row, or change one slot without mutating.
sort()
Puts values in order. Changes the original array.
const a = [3, 1, 4, 1];
// ——— numbers ascending ———
a.sort((x, y) => x - y); // [1, 1, 3, 4]
// ——— numbers descending ———
a.sort((x, y) => y - x);
// ——— default string order (avoid for numbers) ———
[10, 2].sort(); // [10, 2] as strings → wrong for numeric intenttoSorted()
Same idea as sort(), but returns a new array.
const a = [3, 1, 4];
// ——— sorted copy; a unchanged ———
const asc = a.toSorted((x, y) => x - y); // [1, 3, 4]
// a is still [3, 1, 4]reverse()
Flips the array end-for-end. Changes the original.
const a = [1, 2, 3, 4];
// ——— in place ———
a.reverse(); // [4, 3, 2, 1]
// ——— reverse a copy instead ———
const flipped = a.slice().reverse();toReversed()
Flips into a new array. Leaves the original alone.
const a = [1, 2, 3];
// ——— reversed copy ———
const b = a.toReversed(); // [3, 2, 1]
// a is still [1, 2, 3]with()
Returns a copy with one index changed.
const a = [1, 2, 3, 4];
// ——— change index 1 in a copy ———
const b = a.with(1, 99); // [1, 99, 3, 4]
// a is still [1, 2, 3, 4]
// ——— negative index from the end ———
const c = a.with(-1, 0); // [1, 2, 3, 0]Transforming
Build a new list from the old one — change, keep, flatten, or fold.
map()
Builds a new array by running a function on every value.
const a = [1, 2, 3];
// ——— change each value ———
const doubled = a.map((v) => v * 2); // [2, 4, 6]
// ——— keep index in the result ———
const pairs = a.map((v, i) => [i, v]);
// ——— clone a 2D grid row-wise ———
const clone = grid.map((row) => row.slice());filter()
Builds a new array with only the values that pass a test.
const a = [1, -2, 3, 0, 4];
// ——— keep positives ———
const pos = a.filter((v) => v > 0); // [1, 3, 4]
// ——— remove nullish ———
const clean = values.filter((v) => v != null);flat()
Flattens nested arrays one or more levels deep.
// ——— one level ———
const a = [1, [2, 3], [4]];
a.flat(); // [1, 2, 3, 4]
// ——— deeper ———
const b = [1, [2, [3, 4]]];
b.flat(2); // [1, 2, 3, 4]flatMap()
Maps each value, then flattens one level.
const words = ['hi', 'yo'];
// ——— split each word into chars ———
const chars = words.flatMap((w) => w.split('')); // ['h', 'i', 'y', 'o']
// ——— map to zero or more items ———
const expanded = [1, 2, 3].flatMap((v) => (v === 2 ? [] : [v])); // [1, 3]reduce()
Walks the array and folds it down to one result (sum, object, and so on).
const a = [1, 2, 3, 4];
// ——— sum ———
const sum = a.reduce((acc, v) => acc + v, 0); // 10
// ——— frequency map ———
const freq = a.reduce((acc, v) => {
acc.set(v, (acc.get(v) ?? 0) + 1);
return acc;
}, new Map<number, number>());
// ——— max ———
const mx = a.reduce((acc, v) => (v > acc ? v : acc), -Infinity);reduceRight()
Same as reduce(), but walks from right to left.
const parts = ['a', 'b', 'c'];
// ——— build from the end ———
const joined = parts.reduceRight((acc, v) => acc + v, ''); // 'cba'forEach()
Runs a function once for every value. Does not build a new array.
const a = [1, 2, 3];
// ——— side effects only ———
a.forEach((v, i) => {
// visit a[i] === v
});
// ——— prefer for...of when you need break/return early ———
for (const v of a) {
if (v < 0) break;
}join()
Turns the array into a single string with a separator between values.
const a = ['a', 'b', 'c'];
// ——— default comma ———
a.join(); // 'a,b,c'
// ——— custom separator ———
a.join(''); // 'abc'
a.join(' → '); // 'a → b → c'
// ——— path-like ———
['users', '42', 'posts'].join('/'); // 'users/42/posts'toString()
Turns the array into a comma-separated string.
const a = [1, 2, 3];
// ——— same idea as join(',') ———
a.toString(); // '1,2,3'
String(a); // '1,2,3'toLocaleString()
Like toString(), but formats numbers and dates for a locale.
const a = [1000, 2000];
// ——— locale-aware numbers ———
a.toLocaleString('en-US'); // '1,000,2,000'
// ——— with options (per element formatting) ———
a.toLocaleString('en-US', { style: 'currency', currency: 'USD' });Keys, values & entries
Loop over indexes, values, or both together.
keys()
Lets you loop over the indexes.
const a = ['x', 'y', 'z'];
// ——— indexes only ———
for (const i of a.keys()) {
// 0, 1, 2
}
// ——— materialize ———
const idxs = [...a.keys()]; // [0, 1, 2]values()
Lets you loop over the values.
const a = ['x', 'y', 'z'];
// ——— values (same idea as for...of on the array) ———
for (const v of a.values()) {
// 'x', 'y', 'z'
}entries()
Lets you loop over [index, value] pairs.
const a = ['x', 'y', 'z'];
// ——— index + value ———
for (const [i, v] of a.entries()) {
// 0 'x', 1 'y', 2 'z'
}Counting & uniqueness
Count how often values appear, or remember which ones you have seen.
new Map()
Starts a key → value store. Often used to count how often each value appears.
// ——— empty map ———
const freq = new Map<number, number>();
// ——— from pairs ———
const m = new Map<string, number>([
['a', 1],
['b', 2],
]);Map.set()
Saves a value under a key.
const freq = new Map<number, number>();
// ——— count frequencies ———
for (const v of nums) {
freq.set(v, (freq.get(v) ?? 0) + 1);
}
// ——— store an index ———
const firstAt = new Map<number, number>();
for (let i = 0; i < nums.length; i++) {
if (!firstAt.has(nums[i]!)) firstAt.set(nums[i]!, i);
}Map.get()
Reads the value stored for a key.
const freq = new Map<number, number>([[7, 2]]);
// ——— read (undefined if missing) ———
const count = freq.get(7); // 2
const missing = freq.get(9); // undefined
// ——— default with ?? ———
const n = freq.get(9) ?? 0; // 0Map.has()
Checks whether a key exists.
const seen = new Map<number, number>();
// ——— first time vs repeat ———
for (const v of nums) {
if (seen.has(v)) {
// already stored
} else {
seen.set(v, 1);
}
}new Set()
Starts a bag of unique values. Great for “have I seen this?” checks.
// ——— empty set ———
const seen = new Set<number>();
// ——— from an array (dedupe) ———
const unique = [...new Set([1, 1, 2, 3])]; // [1, 2, 3]Set.add()
Adds a value if it is not already there.
const seen = new Set<number>();
// ——— mark visited ———
for (const v of nums) {
seen.add(v);
}
// ——— add returns the set (chainable) ———
seen.add(1).add(2);Set.has()
Checks whether a value is already in the set.
const seen = new Set([1, 2, 3]);
// ——— membership ———
if (seen.has(2)) {
// yes
}
// ——— two-sum style complement ———
const need = target - x;
if (seen.has(need)) {
// found a pair
}
seen.add(x);