cory.kelly
11/19/2019 - 3:58 PM

Converting an array to an object

import "./styles.css";

// 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;
  }, {});
};

const createIdIndex = indexArrayBy("id");
const createEmailIndex = indexArrayBy("email");

const people = [
  {
    id: "7d6f7cf1-6d88-4d51-9421-8167b3fa0152",
    firstName: "Ania",
    lastName: "Repper",
    email: "arepper0@goo.gl"
  },
  {
    id: "fab6d4d2-b27c-4002-aa1f-9a703084632e",
    firstName: "Faulkner",
    lastName: "Tilliard",
    email: "ftilliard1@dion.ne.jp"
  },
  {
    id: "518361a7-ac27-4858-bfb2-8774149d194e",
    firstName: "Fritz",
    lastName: "Lindmark",
    email: "flindmark2@psu.edu"
  }
];

const peopleIdIndex = createIdIndex(people);
const peopleEmailIndex = createEmailIndex(people);

const getPersonById = id => peopleIdIndex[id];
const getPersonByEmail = email => peopleEmailIndex[email];

const faulkner = getPersonById("fab6d4d2-b27c-4002-aa1f-9a703084632e");
const ania = getPersonByEmail("arepper0@goo.gl");

document.getElementById("app").innerHTML = `
  <h2>By Id</h2>
  <pre><code>${JSON.stringify(peopleIdIndex, null, 2)}</code></pre>
  <hr />
  <h2>By Email</h2>
  <pre><code>${JSON.stringify(peopleEmailIndex, null, 2)}</code></pre>
  <hr />
  <h2>Faulkner</h2>
  <pre><code>const faulkner = getPersonById('fab6d4d2-b27c-4002-aa1f-9a703084632e')</code></pre>
  <pre><code>${JSON.stringify(faulkner, null, 2)}</code></pre>
  <hr />
  <h2>Ania</h2>
  <pre><code>const ania = getPersonByEmail('arepper0@goo.gl')</code></pre>
  <pre><code>${JSON.stringify(ania, null, 2)}</code></pre>
`;