JavaScriptFundamental (ES6), part 1
Map vs object key order in JavaScript
59 Map insertion order against object key order
fairInsert the same four keys, three integer-like and one not, into a plain object and into a Map, and compare the order they come back in. Then show what re-setting an existing Map key does to its position, and what deleting and re-adding does.
Stuck? Three hints, smallest first
- 1. An object puts integer-like keys first, in ascending numeric order, whatever order you added them.
- 2. A Map has no such rule: it is strictly insertion order, and the key types are preserved.
- 3. Overwriting a Map key keeps its place. Deleting it and setting it again does not.
const asObject = {};
asObject[3] = 'third';
asObject[1] = 'first';
asObject.zone = 'B';
asObject[2] = 'second';
const objectOrder = Object.keys(asObject);
const asMap = new Map();
asMap.set(3, 'third').set(1, 'first').set('zone', 'B').set(2, 'second');
const mapOrder = [...asMap.keys()];
const mapKeyKinds = mapOrder.map((k) => typeof k);
const objectKeyKinds = objectOrder.map((k) => typeof k);
const reset = new Map([['a', 1], ['b', 2], ['c', 3]]);
reset.set('a', 99);
const afterOverwrite = [...reset.keys()];
reset.delete('b');
reset.set('b', 2);
const afterDeleteAndSet = [...reset.keys()];
const counts = [Object.keys(asObject).length, asMap.size];
const inheritedOnObject = 'toString' in {};
const inheritedOnMap = new Map().has('toString');
console.log('object order:', objectOrder, objectKeyKinds);
console.log('map order :', mapOrder, mapKeyKinds);
console.log('overwrite :', afterOverwrite, '| delete then set:', afterDeleteAndSet);
console.log('counts :', counts);
console.log('inherited : object', inheritedOnObject, '| map', inheritedOnMap);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an object sorts integer-like keys ascending and leaves the rest after them', objectOrder, ['1', '2', '3', 'zone']);
test('a Map returns keys in the order they went in', mapOrder, [3, 1, 'zone', 2]);
test('and keeps their types, where an object stringifies every one', [mapKeyKinds, objectKeyKinds], [['number', 'number', 'string', 'number'], ['string', 'string', 'string', 'string']]);
test('overwriting a value leaves the key where it was', afterOverwrite, ['a', 'b', 'c']);
test('but deleting and re-adding moves it to the end', afterDeleteAndSet, ['a', 'c', 'b']);
test('the values survived the overwrite and the re-add', [reset.get('a'), reset.get('b')], [99, 2]);
test('size is a property on a Map and a count you compute on an object', counts, [4, 4]);
test('and an empty Map has no inherited keys to trip a lookup', [inheritedOnObject, inheritedOnMap], [true, false]);
Object key order is specified, and the specification is stranger than most people expect: integer-like keys first in ascending numeric order, then string keys in insertion order, then symbols. So an object built from ids [3, 1, 2] reads back 1, 2, 3, and there is nothing you can do about it. Exercise 37 hit the same wall when inverting a table of rents.
A Map has one rule — insertion order — and it never touches your keys, so the number 3 stays a number. The two ordering assertions in the middle are the practical ones: overwriting a keeps its position, which is what you want for a cache or an ordered form; deleting and re-adding sends it to the back, which is exactly how you would implement least-recently-used eviction. Reach for a Map whenever the order of arrival is part of the meaning.