JavaScript objects have no order stored for properties (according to the spec). Firefox seems to preserve the order of definition of properties when using a for...in
loop. Is this behaviour something that I can rely on? If not is there a piece of JavaScript code somewhere that implements an ordered hash type?
A hash function is a method or function that takes an item's key as an input, assigns a specific index to that key and returns the index whenever the key is looked up. This operation usually returns the same hash for a given key.
An ordered hash is a compound data type that contains key-value pairs of different data types, including any mixture of scalars, arrays, structures, pointers, object references, dictionaries, lists, hashes, and other ordered hashes.
There exist two components of Hash tables in JavaScript: an “Object” and a “Hash Function”: Object: An object contains the hash table in which the data is stored. It holds all the “key-value” pairs of the hash table.
Comparing JavaScript Object Keys to Arrays To illustrate that JavaScript object keys are not ordered, let's compare them to an array: a simple list of items in a specific order. JavaScript arrays have a defined order from index 0 to the last item in the list, and items added to the array using .
JavaScript in 2016, specifically EcmaScript 6, supports the Map
built-in class.
A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.
That's what you need. (I wonder why that is the first info in the description of this data structure, though.)
For example,
m = new Map() m.set(3,'three') m.set(1,'one') m.set(2,'two') m // Map { 3 => 'three', 1 => 'one', 2 => 'two' } [...m.keys()] // [ 3, 1, 2 ]
or the example from the docs:
var myMap = new Map(); myMap.set(0, 'zero'); myMap.set(1, 'one'); myMap // Map { 0 => 'zero', 1 => 'one' } for (var [key, value] of myMap) { console.log(key + " = " + value); } for (var key of myMap.keys()) { console.log(key); } for (var value of myMap.values()) { console.log(value); } for (var [key, value] of myMap.entries()) { console.log(key + " = " + value); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With