Uthman
Uthman

Reputation: 9817

Efficient method of getting key from value in javascript

First, this question is not a duplicate of Most efficient method to get key for a value in a dict for the inquirer there asked about python and also because I want to discuss if solution given below makes sense and if it is fine to go about such a problem.

So, let's suppose, I have following a following datastructure:

{ 
   "one" : "1",
   "two" : "2",
   .
   .
   "hundred thousand" : "100000"
}

Now, I want to able to get key against a particular value (assuming that I will not have same values for different keys). One solution is to get key by iterating the data but how efficient can become our code if we structure our data as:

 data = [
    { 
       "one" : "1",
       "two" : "2",
       .
       .
       "hundred thousand" : "100000"
    },
    { 
       "1" : "one",
       "2" : "two",
       .
       .
       "100000" : "hundred thousand"
    }
   ]

So, now data[0]."two" can be used to get value of two. But, let's suppose there is a scenario in which I know the value as 999 and I want to know it's key so to get its key I will do data[1]."999" i.e. I will use the reversed data in data[1].

This solution is perhaps faster than iterating over data to find right key. What do you think?

Upvotes: 1

Views: 698

Answers (2)

Ben Taitelbaum
Ben Taitelbaum

Reputation: 7403

You're correct that iterating over all the keys is inefficient, and the method you propose of keeping a reverse lookup hash around is the most common one I've seen for solving this problem. The best solution, of course, is to have a design where you don't need to perform the reverse lookup.

If you're storing a small number of keys, and performing this lookup infrequently, then you're probably fine with the O(n) cost (of course, in that case, maintaining a reverse lookup hash doesn't hurt much either). On the other extreme, where you have millions of keys and can't take the memory hit of having a reverse lookup hash, you could use something like Bloom Filters to help reduce the cost of lookups.

Upvotes: 2

casablanca
casablanca

Reputation: 70711

There isn't a general solution to your problem since multiple keys can have the same value. For your specific example, if you're talking about efficiency in terms of speed, then yes, your current solution of having a reverse map is the fastest way to do it (at the expense of additional space for storing the reverse map).

Upvotes: 0

Related Questions