8

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?

Learner
  • 261
  • 1
  • 4
  • 16

2 Answers2

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