0

Ex: I have a list off User object. Each user have an unique id.

{
  id: 'someid' // uuid,
  name: 'username',
  //... more
}

My question is: Array or Object will be better for list of User.

If use array:

[
  {
      id: 'someid1' // uuid,
      name: 'username',
      //... more
  },
  {
      id: 'someid2' // uuid,
      name: 'username',
      //... more
  },
]

If use Object:

{
  someid1: {
    name: 'username',
    // ... more
  },
  someid2: {
    name: 'username',
    // ... more
  }
}

If I use Object, I can use userId as key(unique). When i want access to a user: users.userid1

If I use Array. I must find first: users.find(user => user.id === 'someid1')

It seem Array doing more than Object (find()).

If I have a lot of user (thousands or millions), the find() take longer to get 1 user.

I dont know how exactly javascript work behind.

2
  • Does this answer your question: stackoverflow.com/questions/17295056/… Commented Oct 29, 2023 at 12:49
  • 1
    Object property lookup will be much faster than array traversal. But there's a third option you haven't listed: Map. See that article for a comparison of using an object vs. using a Map. Commented Oct 29, 2023 at 12:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.