Skip to content

Instantly share code, notes, and snippets.

@meetzaveri
Created November 18, 2019 07:35
Show Gist options
  • Save meetzaveri/f31f572676ec216576384dc9b76f2abd to your computer and use it in GitHub Desktop.
Save meetzaveri/f31f572676ec216576384dc9b76f2abd to your computer and use it in GitHub Desktop.
Convert array of objects to unique based index - value object

// Memorize this function! Be able to transform an array of objects into // a normalized object based on a key. Looking up an item in an array is a O(n) // operation if you don't know the item's index. If you know a value on the // item, and that value is unique, you can create an index based on that value // to enable you to do O(1) look ups

const indexArrayBy = key => array => {
  return array.reduce((acc, cur) => {
    acc[cur[key]] = cur;
    return acc;
  }, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment