-1

I would like to link integer => something in JavaScript without need of iterating over each element of array. In PHP for example I can use arbitrary values without making array bigger.

Let's say my test JS code would be

let experiment = [];
experiment[1] = "hello";
experiment[1000] = "world";
console.log(experiment);

Given this example code, that array contains many empty elements, which implies it's not correct way to do this. I could in theory do array of objects where {int:1,val:'hello'} but this would require me to iterate over said array to access one of elements, which is not what I need.

Is there better way to do this in JavaScript? If not, how bad is that method, like what's the amount of wasted memory for this?

Gall Annonim
  • 263
  • 2
  • 10
  • 2
    If you don’t want *continuous numeric indices* but rather *key-value pairs*, you want an object, not an array. PHP’s arrays combine characteristics of both, not so Javascript. – deceze Aug 21 '20 at 08:40
  • Does this answer your question? [Are Javascript arrays sparse?](https://stackoverflow.com/questions/1510778/are-javascript-arrays-sparse) – jonrsharpe Aug 21 '20 at 08:43
  • @deceze yes, I am aware of that, and I'm looking how to work around it, and get php-like array into javascript. – Gall Annonim Aug 21 '20 at 08:43
  • 1
    @GallAnnonim thats a stupid goal - using the same data type for both stacks and dictionaries is one of the biggest language design failures of PHP. – max Aug 21 '20 at 08:44
  • @jonrsharpe this answers my question only partially. It anwsers "how *bad* is that method", not how to achieve given result. Thank you for suggestion though. – Gall Annonim Aug 21 '20 at 08:54
  • @max Personally, I believe that if something solves given problem it shouldn't be called out as failure in solving given problem. It's not place to argue if PHP approach is better or worse. It was simply example – Gall Annonim Aug 21 '20 at 09:09

2 Answers2

2

Change experiment = [] to experiment = {}.

goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • 3
    It would be better for readers if you could explain how this helps. I know but many readers will not. – Rajesh Aug 21 '20 at 08:45
  • I didn't know that you can use objects with array syntax which allows using arbitrary value. That was missing part of puzzle for me. – Gall Annonim Aug 21 '20 at 08:48
2

You want use an object instead of array. You need not iterate over all keys to find the value. For example experiment[1000] will find the value "world" in constant time O(1) complexity.

let experiment = {};
experiment[1] = "hello";
experiment[1000] = "world";
console.log(experiment);
console.log(experiment[1]);
console.log(experiment[1000]);
Rahul Bhobe
  • 4,165
  • 4
  • 17
  • 32