Array Methods — JavaScript interview guide
Array Methods
map, filter, reduce, find, some, every, flat and sort solve most data-shaping tasks in UI code. Know which ones change the original array.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
reduce and filter, one item at a time
▶const prices = [100, 250, 50];23const total = prices.reduce((sum, p) => {4return sum + p;5}, 0);6console.log(total);78const costly = prices.filter((p) => p > 80);9console.log(costly);
| prices | [100, 250, 50] |
| total | <uninitialized> |
| costly | <uninitialized> |
nothing printed yet
What happens:An array of three prices. We will add them up with reduce, then keep only the big ones with filter.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Common methods
map → same length, transformed. filter → fewer items. reduce → one value. find → first match. some/every → boolean.
const cart = [{ price: 100, qty: 2 }, { price: 50, qty: 1 }];
const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0); // 250
const cheap = cart.filter((i) => i.price < 80);
const names = users.map((u) => u.name);Mutating vs non-mutating
push, pop, shift, unshift, splice, sort, reverse change the original array — dangerous with React state.
Use the copying versions: toSorted, toReversed, toSpliced, with, or [...arr].sort().
[10, 1, 2].sort(); // [1, 10, 2] — sorts as strings!
[10, 1, 2].sort((a, b) => a - b); // [1, 2, 10]Remember this
- Default sort compares strings.
- Never mutate React state arrays.
- reduce with no initial value uses the first item.
Interview questions
Difference between map and forEach?
map returns a new array of results; forEach returns undefined and is only for side effects.
Practice
- Group an array of objects by a key using reduce.
- Count word frequencies in a sentence.