Jude Niroshan
Jude Niroshan

Reputation: 4460

HashMap example in pure JavaScript

I have String like below.

10=150~Jude|120~John|100~Paul@20=150~Jude|440~Niroshan@15=111~Eminem|2123~Sarah

I need a way to retrieve the string by giving the ID.

E.g.: I give 20; return 150~Jude|440~Niroshan.

I think I need a HashMap to achieve this.

Key > 20

Value > 150~Jude|440~Niroshan

I am looking for an pure JavaScript approach. Any Help greatly appreciated.

Upvotes: 4

Views: 6067

Answers (2)

Tushar
Tushar

Reputation: 87203

If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.

Creating an object is better choice in your case.

  1. Split the string by @ symbol
  2. Loop over all the substrings from splitted array
  3. In each iteration, again split the string by = symbol to get the key and value
  4. Add key-value pair in the object
  5. To get the value from object using key use array subscript notation e.g. myObj[name]

var str = '10=150~Jude|120~John|100~Paul@20=150~Jude|440~Niroshan@15=111~Eminem|2123~Sarah';

var hashMap = {}; // Declare empty object

// Split by @ symbol and iterate over each item from array
str.split('@').forEach(function(e) {
  var arr = e.split('=');

  hashMap[arr[0]] = arr[1]; // Add key value in the object
});

console.log(hashMap);

document.write(hashMap[20]); // To access the value using key

Upvotes: 3

Stranded Kid
Stranded Kid

Reputation: 1395

If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.

Upvotes: 2

Related Questions