0

Say I am storing the currentMin each iteration like this in a Map

StoreCurrentMin.set(StoreIandJ[counter],currentMin);

where StoreIandJ[counter] is an array , which is used as key and changes on iterations.

Later I am doing this

var values_array = Array.from( StoreCurrentMin.values() );

which forms an array of all values in the map.

Now my questions is , the value in this map can be duplicates , say they are 2,3,4,2,2 how would I get back keys for all instances of 2

3
  • Possible duplicate of JavaScript object get key by value Commented Jun 13, 2017 at 16:05
  • 2
    How about using StoreCurrentMin.entries() instead of StoreCurrentMin.values() and avoiding the inverse search for keys? Commented Jun 13, 2017 at 16:07
  • Maybe use MultiMap. Here is an example collectionsjs.com/multi-map Commented Jun 13, 2017 at 16:10

2 Answers 2

2

Actually executing .values() and .forEach was enough , didn't realize it before. But thanks all for replying.

var values_array = Array.from( StoreCurrentMin.values() );
var min=Math.min.apply(Math,values_array);

   StoreCurrentMin.forEach(function(value, key) {

       if (value===min){
         console.log (key);
       }
    }); 
Sign up to request clarification or add additional context in comments.

1 Comment

I have an array as a value and 'String' as a key now I would like to know if a particular entry inside an array is already there with the value array of another string key For Ex: var map = { Key1: ["1234","1111","1456"], Key2: ["1001","1234","5001"] } how am I supposed to check that "1234" is the entry having 2 different keys. Thanks,
1

Your values would come back as an array of arrays. Your keys would come back on the zero index of each array. However, you will need to push into the array whenever the value is already hashed. More importantly, you will need to set the value as an object array, in order to be able to push into it when no hash exists. Otherwise, you will overwrite the value and lose its count.

var num = [50, 2, 20, 4, 20, 6, 2, 3, 7, 8, 9];
var mapped = new Map();
for (let n of num) {
  var values = mapped.get(n)
  if (values) values.push(n);
  else mapped.set(n, [n]);
}
var arr = Array.from(mapped);
var key = arr.filter(x => x[0] === 2)
console.log(key);

1 Comment

@user1207289 if this did not help let me know

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.