Javascript Fundamentals · Array Methods

Flatten nested arrays

flat

Flatten nested arrays

You have a list where some items are themselves lists — orders grouped by customer, comments grouped by post — and you want one flat list to loop over. The built-in flat does that: it returns a new array, copying elements out of inner arrays up to a chosen depth; the original array is untouched.

const nested = [1, [2, 3], [4, [5]]];

nested.flat(); // [1, 2, 3, 4, [5]]
nested.flat(2); // [1, 2, 3, 4, 5]
nested.flat(Infinity); // [1, 2, 3, 4, 5]

With no argument, depth defaults to 1, so exactly one level of nesting is removed and the inner [5] stays put. Pass a larger number to go deeper, or Infinity to flatten however deep the nesting goes. Once depth runs out, nested arrays are kept as elements.

flatMap is the common pairing: it maps first and then flattens one level, so a callback can return zero, one, or many values per input.

[1, 2, 3].flatMap((value) => [value, value * 10]); // [1, 10, 2, 20, 3, 30]

Both methods build a fresh array rather than editing the input, so callers never see their data rearranged.

Export flattenOnce from index.js. Called with an array, it returns a new array with exactly one level of nesting removed.

Challenge

You have a list where some items are themselves lists, and you want one level of grouping removed without losing the deeper nesting. Export flattenOnce from index.js.

Your function takes an array and returns a new array with exactly one level of nesting removed, using the built-in flat. Nesting deeper than one level must survive — only the outermost inner arrays are unwrapped. The original array must not be changed.

index.js
export function flattenOnce(list) {
  return list;
}

export function render(mount) {
  const nested = [1, [2, 3], [4, [5]]];

  mount.innerHTML = `
    <p>Nested: ${JSON.stringify(nested)}</p>
    <p>Flattened once: ${JSON.stringify(flattenOnce(nested))}</p>
  `;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.