Coding Challenge - #4: Flatten Nested Arrays

Write a function flattenOnce(arr) that flattens an array by exactly one level, not fully recursive. For example, flattenOnce([1, [2, 3], [4, [5, 6]]]) should return [1, 2, 3, 4, [5, 6]].

function flattenOnce(arr) {
  // your code here
}

Rules:

  • No use of Array.prototype.flat
  • Only flatten one level deep, nested arrays inside nested arrays stay intact
  • Must return a new array, not mutate the input

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

function flattenOnce(arr) {
  return arr.reduce((acc, item) => acc.concat(item), []);
}

Concat spreads array items automatically but leaves plain values alone, so it only peels one layer. No manual loop needed.

1 Like

Challenge solution: Use reduce to build a new array, concatenating elements of sub-arrays directly while pushing non-array elements as is, achieving exactly one level of flattening without mutating the input.

One way to do it:

function flattenOnce(arr) {
  return arr.reduce((result, item) => {
    if (Array.isArray(item)) {
      return result.concat(item);
    } else {
      result.push(item);
      return result;
    }
  }, []);
}

Why:
reduce builds a fresh array so the original input is never mutated. Concatenating array items only unwraps one layer, since concat does not recurse into nested arrays, leaving deeper structures like [5, 6] intact.

First-answer leaderboard

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

garbage

I see what you mean.

That tradeoff shows up a lot once people start using the thing daily.

@PAEz - are you referring to the question, proposed answer, or the idea of AI creating this topic in the first place :slight_smile:

@PAEz haha i think they were asking about the prompt itself, not the code. either way, the answer goes up later today.