Lesson 19 of 34 · Arrays
JavaScript Arrays Boss: The Hoarding Wyrm
Vexgold the Hoarding Wyrm blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Vexgold the Hoarding Wyrm sleeps on a mountain of treasure, but some of it is cursed. Appraise the hoard before you strike, or the curses will strike you first.
Battle plan
The wyrm's hoard is an array of pairs. Each pair is a two-item array holding an item's name and its value in gold. Cursed items have a negative value:
const hoard = [
["gold coins", 300],
["cursed ring", -50],
["dragon crown", 900],
];
You can destructure each pair right in a callback's parameter list. That's much more readable than pair[0] and pair[1]:
hoard.map(([name, value]) => `${name}: ${value}`);
// [ 'gold coins: 300', 'cursed ring: -50', 'dragon crown: 900' ]
hoard.filter(([, value]) => value > 100); // skip the name with an empty slot
You'll need almost every tool from this chapter: reduce to total values, filter and map to pick out names, some/every to check for curses, a non-mutating sort for rankings, and rest parameters plus spread to add treasure. Never modify the hoard you receive. The wyrm notices everything.
Assignment
Write five functions. Every hoard argument is an array of [name, value] pairs.
totalValue(hoard)returns the sum of all values, cursed (negative) items included. An empty hoard is worth0.cursedItems(hoard)returns an array with the names of all items with a negative value, in their original order.mostValuable(hoard, count)returns an array with the names of thecountmost valuable items, highest value first. It must not change the order ofhoard.isSafe(hoard)returnstrueif the hoard contains no cursed items (an empty hoard is safe).addTreasure(hoard, ...newItems)takes any number of new[name, value]pairs and returns a new hoard with them added at the end. The original hoard must not change.
With the hoard used in the tests:
const hoard = [
["gold coins", 300],
["cursed ring", -50],
["dragon crown", 900],
["ruby", 450],
["haunted mirror", -80],
["silver cup", 120],
];
totalValue(hoard); // 1640
cursedItems(hoard); // ["cursed ring", "haunted mirror"]
mostValuable(hoard, 2); // ["dragon crown", "ruby"]
isSafe(hoard); // false
addTreasure(hoard, ["opal", 200]); // a new array with 7 pairsPremium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .