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.
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.
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.