3

I was dealing with a problem and got to the point where I thought I could use the Ids to my entity instances as array indices for easy lookup.

var myArray = [];
myArray[obj.Id] = true;

Assume obj.Id is 1000 here, so will be myArray.length. Am I allocating 1000 bytes for a single boolean value here or is it just returning the maximum index as length?

2
  • 2
    Why not use a key value style object, var myArray = {}; myArray[obj.Id] = true; Commented Mar 29, 2016 at 5:08
  • 2
    it's "returning the maximum index as length", but sparse arrays slow down [].map() and for(i=0;i<myArray.length;i++)-style loops... Commented Mar 29, 2016 at 5:16

1 Answer 1

2

It won't be allocating so many bytes.

But what you are really looking for is an key-value object like

var myObj = {};
myObj[obj.Id] = true;
//then to access
console.log(myObj[obj.Id])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Yes I did use the object approach eventually. I was just interested to know if array space allocation is based on index.
And could you please explain why is using objects rather than array is a better approach then?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.