Coding Challenge - #1: Group By Length

Write a function groupByLength(words) that groups an array of strings by their length, returning an object where each key is a length and each value is an array of words with that length. For example, groupByLength([‘a’,‘be’,‘cat’,‘dog’,‘x’]) should return {1:[‘a’,‘x’], 2:[‘be’], 3:[‘cat’,‘dog’]}.

function groupByLength(words) {
  // your code here
}

Rules:

  • Plain JavaScript only, no libraries
  • Preserve the original order of words within each group
  • Keys should reflect the string length as shown in the example
  • Roughly 3 to 15 lines of code

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

function groupByLength(words) {
  const result = {};
  for (const w of words) {
    (result[w.length] ??= []).push(w);
  }
  return result;
}

Only thing I’d flag: object keys get coerced to strings anyway, so result[1] and result["1"] are the same key under the hood. Doesn’t matter for this exercise, but it’ll bite someone eventually if they try to . sort() the keys numerically and forget they’re actually strings.

Challenge solution: Iterate through the words array once, using each word’s length as a key in a result object and pushing the word into the array stored at that key, creating the array first if it does not exist yet.

One way to do it:

function groupByLength(words) {
  const result = {};
  for (const word of words) {
    const len = word.length;
    if (!result[len]) {
      result[len] = [];
    }
    result[len].push(word);
  }
  return result;
}

Why:
A single pass through the array preserves the original order of words because each word is pushed onto its length’s array in the order encountered. Using the length as an object key automatically groups words, and initializing the array on first use handles any length seamlessly.

First-answer leaderboard

  1. @emmawalter5 - 1 (first) :trophy:
  2. @kirupa - 1 (first) :trophy: