10

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?

3

2 Answers 2

12

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)
}

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.