Kyle Shevlin

Software Engineer

Snippet

indexByKey()

edit
0 strokes bestowed
const indexByKey = key => arr =>
  arr.reduce((acc, cur) => {
    acc[cur[key]] = cur
    return acc
  }, {})

Use this function to make look ups based on a key for an array of items O(1). So long as your list doesn't change, you should only have to run this once.

Here's an example:

const indexById = indexByKey('id')

const members = [
  { id: 1, name: 'Kyle' },
  { id: 2, name: 'Krios' }, // my cat
  { id: 3, name: 'Tali' }, //  my other cat
]

const membersById = indexById(members)
/*
  {
    '1': { id: 1, name: 'Kyle' },
    '2': { id: 2, name: 'Krios' },
    '3': { id: 3, name: 'Tali' }
  }
*/

Make sure the key you're using is unique to each object, otherwise you'll have an incorrect index due to key collisions.


Finished reading?

Here are a few options for what to do next.

Like
Liked the post? Click the beard up to 50 times to show it
Share
Sharing this post on Twitter & elsewhere is a great way to help me out
Support
Was this post valuable to you? Make a donation to show it
Make a Donation
Kofi logo

Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, React and front end web development.

Let's talk some more about JavaScript, React, and software engineering.

I write a newsletter to share my thoughts and the projects I'm working on. I would love for you to join the conversation. You can unsubscribe at any time.

Array.reduce() Logo
Array.reduce()

Check out my courses!

Liked the post? You might like my courses, too. Click the button to view this course or go to Courses for more information.
I would like give thanks to those who have contributed fixes and updates to this blog. If you see something that needs some love, you can join them. This blog is open sourced at https://github.com/kyleshevlin/blog
alexloudenjacobwsmithbryndymentJacobMGEvanseclectic-codingjhsukgcreativeerikvorhesHaroenvmarktnoonandependabotmarcuslyonsbrentmclarkfederico-fiorinimedayzDoNormal
©2021 Kyle Shevlin. All Rights Reserved.