I want add key value pair list in Map and insertion order should be mentioned of that list. So this thing can be done by using LinkedHashMap but I want this implementation in JavaScript. Is javascript support for LinkedHashMap? Can we use LinkedHashMap in javaScript?
Asked
Active
Viewed 6,385 times
8
-
Well...you could always write your own implementation, using the Java source for `LinkedHashMap` as a reference. – Tim Biegeleisen Aug 10 '20 at 05:10
-
1https://stackoverflow.com/questions/25041814/how-to-preserve-order-of-hashmap-in-javascript : may be this helps. It is for ES6 standard – NightLight Aug 10 '20 at 05:10
-
https://github.com/kennyki/linked-hash-map/blob/master/src/linked-hash-map.js – bill.gates Aug 10 '20 at 05:32
2 Answers
11
The new Map
object can do this for you. It will remember the original insertion order of the keys.
Example:
let contacts = new Map()
contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
contacts.has('Jessie') // true
contacts.get('Hilary') // undefined
contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete('Raymond') // false
contacts.delete('Jessie') // true
for (let [key, value] of contacts) {
console.log(key + ' = ' + value.phone + ' ' + value.address)
}

Dieterg
- 16,118
- 3
- 30
- 49
1
There is no need. Map items are already guaranteed to iterated by insertion order.
See Map:
The keys in Map are ordered. Thus, when iterating over it, a Map object returns keys in order of insertion.
There are similar guarantees for normal objects:
Since ECMAScript 2015, objects do preserve creation order for string and Symbol keys [.. and] iterating over an object with only string keys will yield the keys in order of insertion.
The internal implementations use a supplementary “linked list” to obtain this behavior even though it is not part of the names.

user2864740
- 60,010
- 15
- 145
- 220