Member-only story
How To Create a Dictionary From an Array in JavaScript
Sometimes, having a single object that contains all elements can simplify the complexity of our code!
Often, I end up with a list of objects and want to find some items on the list using a unique identifier. One example: enhancing other data that relates to an item on my list.
There are many ways to do this, but some are better than others, especially when there is a lot of data.
Let’s see with a simple example:
An abbreviate list of provinces and territories of Canada. For this example, the provinces only have two attributes, but they have more in real life.
If we want to retrieve the province's name identified by the id 10
, how do we do it?
const province10 = `?`;
Let’s see some solutions we could use!
Solution #0 — Using find
A simple solution could be to use the find
function to retrieve the first element that satisfies our search:
const province10 = data.find(element => element.id === 10);
This works perfectly, but it may not be quick if you need to find many items and/or multiple times. Let’s see if we can do better.
Solution #1 — Using reduce
What if we had the following data in our hands:
{
3: {id: 3, name: 'New Brunswick'},
8: {id: 8, name: 'Ontario'},
10: {id: 10, name: 'Quebec'},
}
Some people call this structure a dictionary or an index. If we had it, we could directly access the element we want using its identifier: dictionary[10]
…