0

Say I just want a variable to hold a bunch of information, and the order is not important. For example, i have a variable players that hold all the information of players in a game. If I use an object to hold all the information, isn't it better than using an array to do so in every possible way?

var players = [{ name: 'john', age: '10' }, { name: 'lily', age: '11' }];

versus

var players = { john: { name: 'john', age: '10' }, lily: { name: 'lily', age: '11' } };

If I count the number of players, or to access/edit a player's information directly, isn't using object better than array in every possible way?

If so, can object literally replace array in any non-ordered situation?

5
  • 4
    You duplicate information and lose order? Doesn't seem like a good trade-off. Commented Aug 3, 2014 at 23:36
  • Better? Depends on your use case. Every way? No. Commented Aug 3, 2014 at 23:40
  • 1
    @elclanrs, since the OP specified that order is not important, I guess if (and only if) he needs to access the data by name rather than by index, it's a good trade-off. Of course, he may not need to duplicate the name (but that really depends on his needs). Commented Aug 3, 2014 at 23:40
  • @jcaron: Still think is not worth it, as you could easily build something like players.filter(where('name', 'john')), and still have a nice collection to work with. Commented Aug 3, 2014 at 23:43
  • 1
    @elclanrs, definitely not the same performance AFAIK. Commented Aug 3, 2014 at 23:47

1 Answer 1

1

You lose access to all of the built-in array methods. What if you ever wanted a sorted list? I can imagine dozens of scenarios where you would want to have an Array.

What do you gain? Access to objects in your array by name? Arrays are objects, so you can just extend the array to get that:

var players = [{ name: 'john', age: '10' }, { name: 'lily', age: '11' }];
players.forEach(function (player) {
    players[player.name] = player;
});
console.log(player[0] === player.john); // true!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.