Keeping the Waiting List in Order

Chloe Park is giving up plot 3, and Rosa’s Python script offers it to the first person on the waiting list: a dict mapping member numbers to names in request order, read with next(iter(waiting)). That relies on a dict keeping every key in insertion order, whatever its type. In the intro video, the line-for-line JavaScript port gave plot 3 to June Harris, who asked last. In this lesson, you’ll see why and what keeps the order.

Port the Waiting List as an Object

Here’s that port again. It uses an object literal and Object.keys(), and now also prints the whole list with Object.values(). In Python, the second output line is Waiting list: Dev Patel, Hannah Cole, Marek Nowak, June Harris. Predict the JavaScript result for that line:

Language: JavaScript
const GIVEN_UP = 3;
const waiting = {
  214: "Dev Patel",
  187: "Hannah Cole",
  305: "Marek Nowak",
  42: "June Harris",
};

const member = Object.keys(waiting)[0];
const winner = waiting[member];
const names = Object.values(waiting).join(", ");
console.log(`Plot ${GIVEN_UP} goes to ${winner} (member ${member})`);
console.log(`Waiting list: ${names}`);

The whole list comes out reordered:

Language: Program Output
Plot 3 goes to June Harris (member 42)
Waiting list: June Harris, Hannah Cole, Dev Patel, Marek Nowak

JavaScript reorders the keys by a fixed rule. An object’s keys are strings (or symbols, which this course doesn’t use), so 214 becomes "214", and an object lists string keys that are array indices first, in ascending order, then the other string keys in the order they were added. Arrays are objects, and they need "0", "1", "2" in order, so member numbers get sorted like indices.

If the booking page loaded the list from JSON text instead, that wouldn’t help. JSON.parse() builds the same kind of object, while Python’s json.loads() keeps the text’s order. Turning that object into a Map afterward can’t bring the order back, since it’s already gone:

Language: JavaScript
const text = `{"214": "Dev Patel", "187": "Hannah Cole",
  "305": "Marek Nowak", "42": "June Harris"}`;
console.log(Object.keys(JSON.parse(text)));

The keys come back sorted:

Language: Program Output
[ '42', '187', '214', '305' ]

Don’t over-apply the rule. Only array indices move: whole numbers from "0" to "4294967294", written without leading zeros. A half plot keyed "7A" or "07" stays where it was added, and so do "-1" and "4294967295".

Keep the Order With a Map

A Map stores its entries apart from its properties, so it keeps every key in insertion order, as a dict does, with 214 still a number. You build one from [key, value] pairs, and that’s also the shape to send when the list travels as JSON: an array such as [[214, "Dev Patel"], [187, "Hannah Cole"]] keeps its order through JSON.parse(), and new Map() takes it as it is. Here’s how the dict operations Rosa’s script uses map onto a Map:

Python JavaScript
for member, name in waiting.items(): for (const [member, name] of waiting)
next(iter(waiting)) [...waiting.keys()][0]
list(waiting.values()) [...waiting.values()]
waiting[member] waiting.get(member)

For a missing key, the last row’s get() returns undefined without an error, as Python’s waiting.get(member) returns None. By contrast, waiting[member] raises a KeyError. The second row differs on an empty list too: next(iter(waiting)) raises StopIteration, but [...waiting.keys()][0] is undefined, and the report would give plot 3 to undefined. Check that waiting.size isn’t 0 before you pick someone.

A Map’s keys() and values() return iterators, which you can’t index, so spreading one into an array literal does what list() does. Iterators are a later topic, so that’s all you need to know about them for now. In the loop, [member, name] takes each pair apart with array destructuring, JavaScript’s equivalent of tuple unpacking:

Language: JavaScript
const GIVEN_UP = 3;
const waiting = new Map([
  [214, "Dev Patel"],
  [187, "Hannah Cole"],
  [305, "Marek Nowak"],
  [42, "June Harris"],
]);

const first = [...waiting.keys()][0];
const winner = waiting.get(first);
const names = [...waiting.values()].join(", ");
console.log(`Plot ${GIVEN_UP} goes to ${winner} (member ${first})`);
console.log(`Waiting list: ${names}`);
console.log(typeof first);
for (const [member, name] of waiting) {
  console.log(member, name);
}

The report now matches Python’s, and the key is still a number:

Language: Program Output
Plot 3 goes to Dev Patel (member 214)
Waiting list: Dev Patel, Hannah Cole, Marek Nowak, June Harris
number
214 Dev Patel
187 Hannah Cole
305 Marek Nowak
42 June Harris

Watch out for porting .items() as Object.entries(waiting): a Map’s entries aren’t properties, so it returns an empty array and the loop runs zero times without an error.

So when key order or key types matter, use a Map, loop over it with for...of, and spread keys() or values() when you need an array. Keep plain objects for records like a plot, whose field names you write in the code.

Next up is the video Updating a Map With set() and delete(). Ola Bakare, member 318, joins the waiting list, and Dev takes plot 3, so you’ll add and remove people.

Become a Member to join the conversation.