0

I want something like this:

var onlineMobilesAnon=[];
onlineMobilesAnon["abc1"]="test";
console.log(onlineMobilesAnon.indexOf("test"));  //Should return "abc1"

How can I achive this ?

Okan
  • 1,379
  • 3
  • 25
  • 38

1 Answers1

1

This isn't exactly what you'd want, since it goes off of keys (Javascript Objects instead of Arrays, though an array is just a special javascript object anyway) and not index, but you could grab all the keys and check the value associated for the key and return that key with the following:

var onlineMobilesAnon = {}
onlineMobilesAnon["abc1"]="test"

var keys = Object.keys(onlineMobilesAnon);

for(var i = 0; i < keys; i++){
  if(onlineMobilesAnon[keys[i]] == "test"){
    console.log(keys[i])
  }
}
Arthur Weborg
  • 8,280
  • 5
  • 30
  • 67
  • 1
    This *is* exactly what he wants. You cannot give string "indexes" to arrays, you're defining keys. What he's writing, `x = []; x['property'] = value`, is incorrect. He shouldn't be using arrays to store arbitrary string/value properties. – user229044 Feb 12 '15 at 18:15
  • I will store 1k value in this list.Is this a good approach ? I will call this each second in node.js What do you think ? – Okan Feb 12 '15 at 18:37
  • I mean, it'll work. Is it best? There are ways to make it faster. However, It would be faster to use number values and `.indexOf(value)` on an array instead of String keys as above above. But if you *MUST* use strings for keys, you cannot use the native array `indexOf()`, you must do something similar to the solution proposed. You could take the above solution farther and optimize it with special searches instead of incremental searching. I'd likely look at a way of using number values and javascript arrays, instead of strings and javascript objects – Arthur Weborg Feb 12 '15 at 19:10
  • Performance is variable [jsPerf1 shows iterative performance of array vs object](http://jsperf.com/performance-of-array-vs-object/17) [jsPerf2 shows direct access performance](http://jsperf.com/array-vs-object-performance). However, if you need to do a search on your datastructure, and performance is essential, I stand on my previous comment that you should try to find a way to use numbers for "indexes" instead of String-Keys. – Arthur Weborg Feb 12 '15 at 19:17