How to Create a Dictionary from an Array in JavaScript

JavaScript arrays are great, but sometimes, having a single object (a dictionary) that contains all elements can significantly simplify the complexity of our code!

3 min read
How to Create a Dictionary from an Array in JavaScript
Photo by Snapwire from Pexels.

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:

const data = [{
  id: 3,
  name: "New Brunswick"
 }, {
  id: 8,
  name: "Ontario"
 }, {
  id: 10,
  name: "Quebec"
 },
];
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 name of the province 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 a lot of items and/or multiple times. Let's see if we can do better. 😋

Array.prototype.find() - JavaScript | MDN
The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

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]. Wouldn't that be easier? 🤔

Let's see how we can create it using one of my favourite array functions: reduce! 🥰

Array.prototype.reduce() - JavaScript | MDN
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
const dictionary = data.reduce((dictionary, province) => {
  dictionary[province.id] = province;
  return dictionary;
}, {});

const province10 = dictionary[10];
// {id: 10, name: 'Quebec'} 

The biggest advantage of this structure is that you only need to iterate on your array one time (to build the dictionary). If you have a lot of data, you should be able to get the element you want faster. 🤑

But, if you're not a fan of functional programming, I've another solution you could use. 😉

Solution #2 - Using object destructuring

While writing this post, I found another elegant solution that I like, but wouldn't use in a good codebase because it's more complex.

const dictionary = Object.assign({}, ...data.map((x) => ({[x.id]: x})));

Do you understand easily this one? Let me help you if not.

const dictionary = Object.assign({}, ...[
    {8: {id:8,name:"Ontario"}},
    {10: {id:10,name:"Quebec"}},
])

This solution use destructuring to create a dictionary with lots of smaller objects. All the generated objects are merged into a simpler one.

More complex, right? 😅

Destructuring assignment - JavaScript | MDN
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Conclusion

I hope this post introduced you to the concept of a JavaScript dictionary and that it helps you in the future! 🤗