Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse lookup object with array

Let say if I have an object like this

resourceMap = {
    "a": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    "b": [11, 12],
    "c": [21, 23],
    "d": [54, 55, 56, 57, 510]
};

What is the best way to figure out if resourceId = 21 would be "c"?

We don't know the key names or number of keys. It only matches once: meaning 21 will belong to only one key "c".

I am thinking of looping through all keys and do indexOf(), but I don't feel it's "elegant" enough.

I could use Underscore but try to avoid and go with what Angular or jQuery or just vanilla Javascript.

like image 330
HP. Avatar asked Oct 07 '14 17:10

HP.


People also ask

How do you reverse an array in JavaScript?

JavaScript Array reverse()The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.

What Reverse () will do in JavaScript?

The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.


2 Answers

It's perfectly acceptable to have numeric property names for objects in JavaScript. We can use this to our advantage to build a second object that maps everything in reverse. This will make lookups inexpensive.

var reverseMap = {};
for(var propName in resourceMap)
{
    var numsArr = resourceMap[propName];
    numsArr.forEach(function(num){
        reverseMap[num]=propName;
    });
}
console.log(reverseMap[54]); //'d'

http://jsfiddle.net/y11sbgbv/

Building the reverseMap can also be done more "functionally" (e.g. without using side-effects) as follows:

var reverseMap2 = Object.keys(resourceMap).reduce((acc, propName) =>          
  resourceMap[propName].reduce((a, num) => {
    a[num] = propName;
    return a;
  }, acc), {});
like image 164
spender Avatar answered Sep 20 '22 23:09

spender


Preprocess into a different look up table

var revMap = []; // or var revMap = {};
Object.keys(resourceMap).forEach(function(key) { 
    resourceMap[key].forEach( function (ind) {
         revMap[ind] = key;   
    });
});
console.log(revMap[21])

or look up on demand:

resourceMap = { "a": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "b": [11, 12], "c": [21, 23], "d": [54, 55, 56, 57, 510] };
function findMapKey (map, ind) {
    var match = null;
    Object.keys(map).some(function(key) {
        var test = map[key].indexOf(ind)!==-1;
        if (test) { 
            match = key; 
        } 
        return test;
    });
    return match;
}
console.log(findMapKey(resourceMap, 21));
like image 35
epascarello Avatar answered Sep 20 '22 23:09

epascarello