Lesson 6 of 50JavaScript basics
Arrays and Objects
Transform data with map, filter and reduce, sort safely, and pick between objects, Map and Set.
Almost all front-end and Node code is data shaping: take the JSON an API sent, filter it, reshape it, count it, sort it, render it. Arrays and objects are how JavaScript holds that data, and their built-in methods are what you will reach for every day. Interviewers expect you to chain map, filter and reduce without thinking.
Arrays: the basics
An array is an ordered list. Indexes start at 0, and length is always one more than the last index.
Press Run (⌘ Enter) to see what happens.Arrays can hold mixed types, and reading a missing index gives undefined rather than throwing. push, pop, shift, unshift and splice mutate the array in place. Most other methods return a new value and leave the original alone, which matters a lot in React, where you must never mutate state.
map, filter, reduce
These three methods replace most hand-written loops.
map(fn)transforms every element and returns a new array of the same length.filter(fn)keeps elements wherefnreturns a truthy value. The new array can be shorter.reduce(fn, start)folds the whole array down to one value (a sum, an object, anything).fnreceives the running total (the accumulator) and the current element.
Four order amounts in dollars. Goal: total tax on orders over $10, at 10%.
Press Run (⌘ Enter) to see what happens.Always pass the starting value to reduce. Without it, reduce uses the first element as the start, and on an empty array it throws a TypeError.
What does this print?
const nums = [1, 2, 3, 4, 5]; const result = nums .filter((n) => n % 2 === 1) .map((n) => n * n) .reduce((a, b) => a + b, 0); console.log(result);
More everyday methods
| Method | Returns | Example |
|---|---|---|
find(fn) | The first match, or undefined | users.find(u => u.id === 7) |
findIndex(fn) | Its index, or -1 | todos.findIndex(t => t.done) |
some(fn) | true if any element passes | cart.some(i => i.outOfStock) |
every(fn) | true if all elements pass | fields.every(f => f.valid) |
includes(x) | true if x is in the array | roles.includes("admin") |
join(sep) | A string | ["a","b"].join(", ") |
slice(a, b) | A copy of part of the array | items.slice(0, 3) |
Pick the method for each job.
Sorting and its trap
sort has a nasty default: with no comparator, it converts elements to strings and sorts them alphabetically. It also mutates the array.
Press Run (⌘ Enter) to see what happens.A comparator (a, b) => number returns a negative number if a should come first, positive if b should, and 0 if they tie. So a - b sorts ascending and b - a descending. For strings use a.localeCompare(b), which handles case and accents properly.
toSorted (ES2023) returns a sorted copy instead of mutating. Its siblings toReversed, toSpliced and with(index, value) do the same for the other mutating methods. Use them whenever the original must stay intact.
[10, 9, 1, 2].sort() return?Objects
An object is a collection of key/value pairs called properties. Keys are strings (or symbols); values can be anything, including functions and other objects.
Press Run (⌘ Enter) to see what happens.Object.keys, Object.values and Object.entries turn an object into arrays, so you can use all the array methods on it. Object.fromEntries goes the other way.
Two ES2015 shortcuts appear everywhere:
Press Run (⌘ Enter) to see what happens.What does this print?
const stock = { apples: 3, pears: 0, plums: 5 };
const inStock = Object.entries(stock)
.filter(([fruit, qty]) => qty > 0)
.map(([fruit]) => fruit);
console.log(inStock.join(" "));Map and Set
Plain objects work as dictionaries, but they have quirks: keys are always converted to strings, they inherit properties like toString, and counting their size takes Object.keys(obj).length. ES2015 added two purpose-built collections.
A Map stores key/value pairs where keys can be any type (numbers, objects, functions), remembers insertion order, and has a size. A Set stores unique values.
Press Run (⌘ Enter) to see what happens.| Use | When |
|---|---|
| Plain object | A fixed shape known in advance ({ id, name, email }), or data you will send as JSON |
Map | A dictionary with keys added at runtime, non-string keys, frequent adds and deletes, or when you need size |
Set | Uniqueness and fast "have I seen this?" checks (has is O(1) on average, array.includes is O(n)) |
One catch: JSON.stringify does not understand Map or Set (it outputs {}). Convert with Object.fromEntries(map) or [...set] before sending them over the network.
groupBy
Write groupBy(items, key). items is an array of objects and key is a property name. Return an object whose keys are the distinct values of that property (as strings) and whose values are arrays of the items in that group, in their original order.
groupBy(
[{ name: "Ada", team: "red" }, { name: "Sam", team: "blue" }, { name: "Leo", team: "red" }],
"team",
);
// { red: [{ name: "Ada", team: "red" }, { name: "Leo", team: "red" }],
// blue: [{ name: "Sam", team: "blue" }] }Do not use the built-in Object.groupBy; build it yourself.
Leaderboard
Write leaderboard(players). Each player is { name, score }. Return an array of names ordered by score, highest first. Players with the same score are ordered alphabetically by name.
leaderboard([
{ name: "Sam", score: 25 },
{ name: "Ada", score: 100 },
{ name: "Leo", score: 25 },
]);
// ["Ada", "Leo", "Sam"]Do not mutate the input array. Watch out for the default sort, which compares strings.
- map / filter / reduce
- Transform each element / keep matching elements / fold everything into one value. None of them mutate the original.
- accumulator
- The running value
reducepasses from one step to the next. Always give it a starting value. - comparator
(a, b) => numberpassed tosort. Negative putsafirst. Usea - bfor numbers.- toSorted
- ES2023 non-mutating version of
sortthat returns a sorted copy. - Map
- Key/value collection with keys of any type, insertion order and a
sizeproperty. - Set
- Collection of unique values with O(1) average
has,addanddelete.