Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 30 min · revision 3

Shaping Data with Objects, Arrays, Map and Set

Turn a raw list of orders into reports: partition and transform with non-mutating array methods, group with Map, and deduplicate with Set.

Contentsand lesson path

What you will learn

  • Model and transform data with objects, arrays, Map and Set using destructuring, spread, optional chaining and non-mutating array methods such as map, filter, reduce and toSorted.

01. The problem

Most frontend work is this task in disguise: data arrives as a flat array, and the screen needs a shape the array does not have yet. This worked example takes a JSON array of orders and produces three reports: units sold per customer, the best-selling products, and a list of invalid records. It is also a small rehearsal of the practice project of this skill, which adds prices and a custom error.

The data. An order has an id, a customer and an items array of { sku, qty } objects. Real feeds are dirty: one order has no customer key at all, one has an empty basket, and one has no items key. A record is valid only when it has a customer and at least one item. One rule shapes everything else: the input array must not change. The reports are new values; the orders stay as they arrived.

02. Step 1: partition valid and invalid records

Reading a property that does not exist does not throw: order.customer is simply undefined when the key is absent. So a missing customer surfaces as a falsy value, and Boolean(order.customer) becomes the honest test — it accepts any non-empty string and rejects both undefined and "".

Going one level deeper is different. Record x11 has no items key, so order.items is undefined, and order.items.length throws TypeError: Cannot read properties of undefined (reading 'length'). One bad record would stop the whole report. Two operators handle it. Optional chaining, ?., looks at the value on its left: if that value is null or undefined, the expression stops and gives undefined instead of throwing, so order.items?.length is undefined for x11. Nullish coalescing, ??, then supplies a fallback for exactly those two values: order.items?.length ?? 0 is 0, and 0 > 0 is false. Unlike ||, which replaces every falsy value, ?? keeps 0, "" and false, so 0 ?? 5 is 0 while 0 || 5 is 5.

JavaScript · step1-validate.js
const item = (sku, qty) => ({ sku, qty }); // a little factory for readability

const orders = [
  { id: 'o1', customer: 'ada', items: [item('usb-c', 2), item('case', 1)] },
  { id: 'o2', customer: 'bo', items: [item('usb-c', 1)] },
  { id: 'o3', customer: 'ada', items: [item('hub', 3), item('case', 1)] },
  { id: 'x9', items: [item('hub', 1)] },
  { id: 'x10', customer: 'cy', items: [] },
  { id: 'x11', customer: 'dee' }, // no items key at all
];

const isValid = (order) =>
  Boolean(order.customer) && (order.items?.length ?? 0) > 0;
const valid = orders.filter(isValid);
const invalid = orders.filter((order) => !isValid(order));

console.log(valid.map((order) => order.id));
console.log(invalid.map((order) => order.id));
Expected output
[ 'o1', 'o2', 'o3' ]
[ 'x9', 'x10', 'x11' ]

filter returns a new array and leaves orders untouched, which is why calling it twice is safe. Note what the invalid list is for: it is a report too, not garbage. The practice project asks for invalid records to be raised as a custom error; here we collect them first and let the caller decide.

03. Step 2: totals per customer with a Map

Grouping by a key is one of the most common data transformations in frontend code, and Map is the structure built for it. A Map stores key–value pairs, adds them with set, reads them with get, and walks its entries in insertion order. The idiom (map.get(key) ?? 0) + n reads the current count, uses the ?? from step 1 to treat a missing key as 0, and writes the new one back in a single line.

The loop head destructures each order into customer and items directly, so the body says what it means. reduce folds the item quantities of one order into a single number.

JavaScript · step2-totals.js (valid orders from step 1)
const unitsByCustomer = new Map();

for (const { customer, items } of valid) {
  const orderUnits = items.reduce((sum, item) => sum + item.qty, 0);
  unitsByCustomer.set(customer, (unitsByCustomer.get(customer) ?? 0) + orderUnits);
}

for (const [customer, units] of unitsByCustomer) {
  console.log(customer, units);
}
Expected output
ada 7
bo 1

Ada ordered 2 + 1 in one basket and 3 + 1 in the other: 7 units. Why a Map and not a plain object? Object keys are strings or symbols, and a Map accepts any value as a key, keeps pairs in the order you inserted them, reports its size with .size, and carries no inherited properties from Object.prototype — so a customer literally named "constructor" cannot break it. Use plain objects for fixed, known fields; use Map when keys arrive from data.

04. Step 3: best sellers with toSorted

The same grouping idiom, now keyed by sku, gives units per product. To rank it, turn the entries into an array with spread (...), then sort. Here the method matters: sort() rearranges in place and, without a comparator, compares values as strings. toSorted(compareFn) is its non-mutating twin — a new array, left in order, original untouched — and the comparator (a, b) => b[1] - a[1] sorts by the second element, the count, descending.

JavaScript · step3-bestsellers.js (valid orders from step 1)
const unitsBySku = new Map();
for (const { items } of valid) {
  for (const { sku, qty } of items) {
    unitsBySku.set(sku, (unitsBySku.get(sku) ?? 0) + qty);
  }
}

const ranking = [...unitsBySku.entries()].toSorted((a, b) => b[1] - a[1]);
console.log(ranking);
console.log(ranking.slice(0, 2).map(([sku, units]) => `${sku}: ${units}`));
Expected output
[ [ 'usb-c', 3 ], [ 'hub', 3 ], [ 'case', 2 ] ]
[ 'usb-c: 3', 'hub: 3' ]

usb-c and hub tie at 3 units; toSorted is stable, so the tie keeps insertion order and usb-c came first. The last line shows destructuring at work twice: [sku, units] unpacks each entry array, and slice takes the head of the ranking without touching it.

05. Step 4: unique values with a Set

The third report needs each customer’s distinct products. Set is a collection of unique values: add is a no-op for a value it already has, has answers membership, and spreading a set gives its values as an array. Nesting a Set inside the Map answers "which, distinctly" while the map answers "for whom" — two small structures instead of one clever tangle.

JavaScript · step4-sets.js (valid orders from step 1)
const skusByCustomer = new Map();

for (const { customer, items } of valid) {
  const seen = skusByCustomer.get(customer) ?? new Set();
  for (const { sku } of items) seen.add(sku);
  skusByCustomer.set(customer, seen);
}

for (const [customer, skus] of skusByCustomer) {
  console.log(customer, [...skus].join(', '));
}

console.log(new Set(valid.flatMap((order) => order.items.map((i) => i.sku))).size);
Expected output
ada usb-c, case, hub
bo usb-c
3

The last line collapses the whole question to a number: flatMap gathers every sku from every order, the Set removes repeats, and its size is the catalogue breadth — 3 products across all customers.

06. Copying instead of mutating

The no-mutation rule has a general tool. Spread { ...obj } and [...array] build shallow copies: one level deep, so a nested array or object is still shared with the original. For a true independent copy, structuredClone deep-copies the value, including nested structures and dates. It copies data, not behaviour: functions cannot be cloned (it throws a DataCloneError), and class instances come back as plain objects without their methods.

JavaScript · step5-nomutate.js
const ids = ['o1', 'o2'];
const withNew = [...ids, 'o3'];        // a new array: ids is untouched
const byId = { o1: 'ada' };
const updated = { ...byId, o2: 'bo' }; // a new object: byId is untouched
console.log(ids, withNew);
console.log(byId, updated);

const nested = { tags: ['new'] };
const clone = structuredClone(nested); // built-in deep copy
clone.tags.push('used');
console.log(nested.tags, clone.tags);
Expected output
[ 'o1', 'o2' ] [ 'o1', 'o2', 'o3' ]
{ o1: 'ada' } { o1: 'ada', o2: 'bo' }
[ 'new' ] [ 'new', 'used' ]

07. Check your understanding

Practice check · 3 questions

Choose and predict the structure

Predict outputs, and say why the method behaves as it does.

Q1. What does this log? const m = new Map(); m.set('a', 1); m.set('b', 2); m.set('a', 9); console.log(m.size, m.get('a'));
Q2. What does this log? const ids = ['x', 'y', 'x', 'z', 'y']; console.log([...new Set(ids)].length);
Q3. What does this log? const parts = ['a', '', 'b', '', 'c']; const kept = parts.filter((p) => p !== ''); console.log(parts.length, kept.length);
Practice only: not graded, not saved, not evidence.

08. Apply it

Extend the worked example towards the practice project:

  1. Add a price to every item and return revenue per customer as a Map, reusing the grouping idiom.
  2. Change the ranking to the two best-selling products per customer, so the value of each Map entry is itself a ranked list. Watch the line length and pull the inner logic into a named function.
  3. Write the same reports twice, once by mutating a result object in place and once with the non-mutating style of this lesson. Then change the order of the two report calls and see which version survives — that fragility is the argument for the rule.

The next data you transform like this will arrive over the network, one promise at a time; the async JavaScript skill covers that waiting part.

09. Review prompt

Without looking back: write the one-line grouping idiom with Map, and say what ?? does inside it. Say what order.items?.length gives for a record without items, and name a value for which ?? and || give different results. Then explain the difference between sort and toSorted, and between a spread copy and structuredClone. Name two reasons Map beats a plain object when keys come from data, and describe what filter, flatMap and slice each return.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check