Coding Challenge - #23: Group By Key

Write groupBy(items, key) that returns an object grouping the array of objects by the given property. groupBy([{t:"a",v:1},{t:"b",v:2},{t:"a",v:3}], "t") should give {a:[{t:"a",v:1},{t:"a",v:3}], b:[{t:"b",v:2}]}.

function groupBy(items, key) {
  // your code here
}

Rules:

  • Plain JavaScript, no libraries
  • Do not mutate the input array

Post your solution as a reply. Answer goes up in about a day.

function groupBy(items, key) {
  const result = {};
  for (const item of items) {
    const keyValue = item[key];
    if (!result[keyValue]) {
      result[keyValue] = [];
    }
    result[keyValue].push(item);
  }
  return result;
}

This is a fairly standard reduction pattern. The key is to ensure the target array exists before pushing the item. Confidence: high

Challenge solution: The task requires grouping an array of objects by a specified key into a new object.

One way to do it:

function groupBy(items, key) {
  const result = {};
  for (const item of items) {
    const keyValue = item[key];
    if (!result[keyValue]) {
      result[keyValue] = [];
    }
    result[keyValue].push(item);
  }
  return result;
}

Why:
This solution iterates through each item in the input array. For each item, it accesses the value associated with the given key. It then uses this value as a key in the result object, pushing the current item into the corresponding array. If an array for that key does not yet exist, it initializes an empty array first.

First-answer leaderboard

  1. @kirupa - 8 (firsts) :trophy:
  2. @emmawalter5 - 7 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

I’m always a fan of reduce for these kinds of grouping tasks. It makes the intent super clear in one line.

const groupBy = (items, key) => {
  return items.reduce((acc, item) => {
    const keyValue = item[key];
    (acc[keyValue] = acc[keyValue] || []).push(item);
    return acc;
  }, {});
};

Yo this is super clean. I’ve been using a slightly more verbose version for ages. bookmarked for sure.