0

I hear a lot about how we should use arrays for things like users list, as it's fast and there are functionalities like length that can be useful etc.

However in many of my use cases, I feel like an object of objects is the way to go and I'd like your opinion. For example, there's a list of users on my real-time app -- the list has to be updated whenever a new user connects or disconnects. Would you use an array or an obj like this in this case? If you use an array, what are the reasons?

var obj = {
    "1": {id:1, fullName: 'My Name', sex: 'male'},
    "50": {id:50, fullName: 'My Name', sex: 'none'},
    "5": {id:5, fullName: 'My Name', sex: 'female'},
};

When a user joins I just add his obj to the obj, and when a user discs, I just use delete obj[50];

If I used an array, I'd have a removeUser(id) function which scans the array and removes the user when it finds it.

jSmith
  • 275
  • 1
  • 4
  • 13

2 Answers2

0

Definitively, you should use objects. While they're not guaranteed to be backed by a hash table, at least they should be always optimized to access properties faster than searching an object in an array (i.e. Array.prototype.filter).

Maybe you want to take a look at this Q&A: Under the hood, are Javascript objects hash tables?

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

Dictionary style from Direct Instance of Object

In your simple case I would use a dictionary as what you have. You can use a for in loop to enumerate the properties if you need. Such as:

var dict = { james: 34, ben: 34, chris: 73};
var people = [];

for (var name in dict){
    people.push(name + ": " + dict[name]);
} 

people; //["alice:34", "bob: 24", "chris: 62"]

Prefer Arrays to Dictionaries for Ordered Collections.

If you need an ordered collection I would prefer an array. Intuitevely, a Javascript object is an unordered collection of properties. Getting and setting different properties should work in any order. The ECMAScript standard does not specify the order of property storage.

The Catch When Using for..in

The for..in loop has to pick some oreder to enumerate an object's properties and since the standard allows Javascript Engines the freedom to choose an order the behavior of your code can change. It may not always be obvious that your behavior is different unless you test your code in different Javascript environments.

Things to Remember

  1. Avoid relying on the order in which for...in loops enumerate object properties if you are going to use objects for your program.
  2. If you aggregate data in a dictionary, make sure the aggregate operations are order-insensitvit.
  3. Use arrays instead of dictionary objects for ordered collections.

Just some things to help you make a decision.

Abdullah Rasheed
  • 3,562
  • 4
  • 33
  • 51