Array methods, spread and destructuring
Chain map, filter and reduce correctly, sort numbers without surprises, and copy arrays and objects instead of sharing them.
Front-end and Node screenings expect you to turn a list of objects into totals, lookups and new shapes without writing index loops. The array methods below, plus spread and destructuring, are the vocabulary. Learn which ones return a new array and which ones change the original.
map, filter, reduce and friends
map transforms every item, filter keeps some, and reduce folds the array into one value. find, some and every answer questions about the array. None of these change the source.
const orders = [
{ id: 1, city: "Pune", amount: 1200 },
{ id: 2, city: "Delhi", amount: 800 },
{ id: 3, city: "Pune", amount: 300 },
];
const puneTotal = orders
.filter(o => o.city === "Pune")
.map(o => o.amount)
.reduce((sum, a) => sum + a, 0);
console.log(puneTotal); // 1500
console.log(orders.find(o => o.amount > 1000)?.city); // Pune
console.log(orders.some(o => o.amount < 500)); // trueRead a chain from top to bottom: each line receives the array the line above returned, so filtering before mapping keeps the work small. Always pass the initial value to reduce. Without it, an empty array throws and the first element is used as the starting total, which is wrong when you are summing a property.
sort changes the array and compares as text
const nums = [10, 9, 100, 1];
console.log([...nums].sort()); // [1, 10, 100, 9]
console.log([...nums].sort((a, b) => a - b)); // [1, 9, 10, 100]sort, push, splice and reverse mutate in place. slice, concat, map and filter return new arrays. Copy with spread before sorting when the original must stay as it is.
Copying and unpacking
const a = [1, 2, 3];
const b = a; // same array
b.push(4);
console.log(a); // [1, 2, 3, 4]
const copy = [...a, 5]; // new array
const base = { theme: "light", lang: "en" };
const updated = { ...base, theme: "dark" };
console.log(updated, base.theme); // { theme: 'dark', lang: 'en' } light
const { city, amount: amt = 0, note = "none" } = orders[0];
console.log(city, amt, note); // Pune 1200 noneSpread makes a shallow copy: nested objects are still shared. Destructuring with a rename (amount: amt) and a default (= 0) is common in function parameters and React props.
Common mistakes and a practice habit
- Sorting numbers without a compare function.
- Writing
["1", "2", "3"].map(parseInt), which gives[1, NaN, NaN]becausemappasses the index as the radix. Usemap(Number).
Practice habit: Take a small JSON array from any project and write five one-line questions about it: total of one field, names of items matching a condition, the first match, whether all pass, and the list sorted by a number. Solve each with a single chain, run it, and repeat with new questions tomorrow.
More in Programming