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

user1207289
  • 3,060
  • 6
  • 30
  • 66
  • Possible duplicate of [JavaScript object get key by value](https://stackoverflow.com/questions/9907419/javascript-object-get-key-by-value) – austin wernli Jun 13 '17 at 16:05
  • 2
    How about using `StoreCurrentMin.entries()` instead of `StoreCurrentMin.values()` and avoiding the inverse search for keys? – le_m Jun 13 '17 at 16:07
  • Maybe use MultiMap. Here is an example http://www.collectionsjs.com/multi-map – Theo Briscoe Jun 13 '17 at 16:10

2 Answers2

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);
       }
    }); 
user1207289
  • 3,060
  • 6
  • 30
  • 66
  • 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, – Abhi Nov 26 '18 at 13:28
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);
Rick
  • 1,035
  • 10
  • 18