DEV Community

Andy
Andy

Posted on

Store array data in keyed-objects for better performance

There are plenty of ways to store client-side data in Javascript and React, not to mention ES6's data structures like Set and Map, but sometimes all you need is a simple object.

I use this pattern almost daily in combination with redux and/or context to streamline data access. I want to demonstrate how we can use a keyed-object to increase performance vs. storing data in a typical array.

Problem Example

Let's say we're fetching an array of people from an API to display a list:

[  
  {
    'id': 1,
    'name': 'Keanu Reeves',
    'bio': 'Bad ass' 
  },
  {
    'id': 2,
    'name': 'Elon Musk',
    'bio': 'Space cowboy' 
  },
  ...
  {
    'id': 20,
    'name': 'Tom Hanks',
    'bio': 'Toy cowboy' 
  },
]
Enter fullscreen mode Exit fullscreen mode

Assuming we store this array somewhere client side, if we wanted to access a particular user by ID, we would need to do something like people.find(x => x.id === 1). This has a time complexity of O(n) and can be expensive if the array is large.

O(n) means the larger the array gets, the longer it can take to find what you're looking for! This is because it has to potentially check every item in the array 👎

Solution Example

By looping through the results in the API response, we can build a keyed-object.

const keyedObject = {};
response.map(person => {
  const {id, ...rest} = person
  keyedObject[id] = rest
});
Enter fullscreen mode Exit fullscreen mode

Added bonus (looping)

If we need to loop through the data to display a list for example, we can create an array to store the IDs.

The final solution might look like this:

const keyedObject = {};
const ids = response.map(person => {
  const {id, ...rest} = person
  keyedObject[id] = rest
  return id
});
Enter fullscreen mode Exit fullscreen mode

Now we can quickly access our data by ID with O(1) time complexity and loop through the data using our ids array.

O(1) is great for performance because no matter how large the array or object is, we can always go straight to the item we want! 👍

const name = keyedObject[personId].name
const allNames = ids.map(id => keyedObject[id].name)
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! 😃

Top comments (0)