javascriptarraysalgorithmtime-complexity

In JavaScript, is it good to declare an Array to store a single value just to facilitate iterating over it?


I have an object where its keys can take a single value or array of values

Example:

sample = {}
sample[key] = "foo"
sample[bar] = ["Alpha", "Bravo", "Charlie"]

I will eventually iterate over this object (sample) and output the values. In this process, I have to check if each value is an Array and if so I'll have to output those values.

Which is a costly operation?

Checking if the value is an array every time while iterating?

if(Array.isArray(arr[prop]))

Or

just make all the keys as arrays, so that I can iterate with ease like,

arr[prop].forEach(function(val){}

Algorithmically, is declaring extra space to facilitate iterating over an object worth it?


Solution

  • If this is a private object, then it doesn't really matter, but it's probably better to favor simple code.

    If this is an interface object, i.e., something that is provided to you as a function argument or through other means, then the distinction is important. If all the keys can be multi-valued then you should just make them arrays, because it makes the interface simpler.