Skip to content

Lesson 6 of 50JavaScript basics

Arrays and Objects

Transform data with map, filter and reduce, sort safely, and pick between objects, Map and Set.

15 min read0/5 questions

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.

JavaScript
const langs = ["Python", "JavaScript", "Go"]; console.log(langs[0], langs.length);console.log(langs.at(-1)); // negative index from the end (ES2022)console.log(langs[10]); // out of range: undefined, not an error langs.push("Rust"); // add to the endconst first = langs.shift(); // remove from the frontconsole.log(first, langs);console.log(langs.includes("Go"), langs.indexOf("Go"));
Output
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 where fn returns 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). fn receives the running total (the accumulator) and the current element.
Order totals: map, filter, then reduce
12
0
45
1
8
2
60
3
step = start

Four order amounts in dollars. Goal: total tax on orders over $10, at 10%.

1/6
JavaScript
const orders = [12, 45, 8, 60]; const totalTax = orders .filter((amount) => amount > 10) .map((amount) => amount * 0.1) .reduce((sum, tax) => sum + tax, 0); console.log(totalTax.toFixed(2));console.log(orders); // untouched
Output
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.

Predict the outputJavaScript

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);
Need a nudge? Hints walk you through it.

More everyday methods

MethodReturnsExample
find(fn)The first match, or undefinedusers.find(u => u.id === 7)
findIndex(fn)Its index, or -1todos.findIndex(t => t.done)
some(fn)true if any element passescart.some(i => i.outOfStock)
every(fn)true if all elements passfields.every(f => f.valid)
includes(x)true if x is in the arrayroles.includes("admin")
join(sep)A string["a","b"].join(", ")
slice(a, b)A copy of part of the arrayitems.slice(0, 3)
Match the pairs0/5 matched

Pick the method for each job.

Choose an item, then its match on the other side.

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.

JavaScript
const scores = [100, 25, 3, 1000];scores.sort();console.log(scores); // strings: "100" < "1000" < "25" < "3" scores.sort((a, b) => a - b);console.log(scores); // numeric ascending const names = ["Sam", "ada", "Leo"];console.log(names.toSorted((a, b) => a.localeCompare(b)));console.log(names); // toSorted did not touch the original
Output
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.

Quick check
What does [10, 9, 1, 2].sort() return?
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
const user = { name: "Ada", age: 36, "favourite-lang": "JS" }; console.log(user.name); // dot accessconsole.log(user["favourite-lang"]); // bracket access for awkward keysconst field = "age";console.log(user[field]); // bracket access with a variable user.email = "ada@example.com"; // adddelete user.age; // removeconsole.log(user); console.log(Object.keys(user));for (const [key, value] of Object.entries(user)) { console.log(`${key} = ${value}`);}
Output
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:

JavaScript
const name = "Leo";const role = "admin";const key = "theme"; const account = { name, // shorthand for name: name role, [key]: "dark", // computed key: the value of key becomes the property name greet() { return `Hi, ${this.name}`; // method shorthand },}; console.log(account.theme, account.greet());
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

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(" "));
Need a nudge? Hints walk you through it.

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.

JavaScript
const visits = new Map();for (const page of ["/home", "/about", "/home", "/home"]) { visits.set(page, (visits.get(page) ?? 0) + 1);}console.log(visits.get("/home"), visits.size);console.log([...visits.entries()]); const tags = new Set(["js", "css", "js", "html", "css"]);console.log(tags.size, tags.has("css"));console.log([...tags]); // dedupe an array in one line
Output
Press Run (⌘ Enter) to see what happens.
UseWhen
Plain objectA fixed shape known in advance ({ id, name, email }), or data you will send as JSON
MapA dictionary with keys added at runtime, non-string keys, frequent adds and deletes, or when you need size
SetUniqueness 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.

Quick check
You need to cache results keyed by the user object itself (not its id). What should you use?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

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.

JavaScript
function groupBy(items, key) { // Walk the items once, pushing each into the right group. return {};}
ChallengeEasy

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.

JavaScript
function leaderboard(players) { // Sort a copy with a comparator, then map to names. return [];}
Key terms
map / filter / reduce
Transform each element / keep matching elements / fold everything into one value. None of them mutate the original.
accumulator
The running value reduce passes from one step to the next. Always give it a starting value.
comparator
(a, b) => number passed to sort. Negative puts a first. Use a - b for numbers.
toSorted
ES2023 non-mutating version of sort that returns a sorted copy.
Map
Key/value collection with keys of any type, insertion order and a size property.
Set
Collection of unique values with O(1) average has, add and delete.