Skip to main content
100%

Flatten an array in Javascript without recursion

✓ Published0🌍 Public
HHypercubed
Last edited Apr 21, 2016
Created on Apr 21, 2016

This example compares two JavaScript functions for flattening nested arrays, showing that the iterative approach is faster than the recursive one. The code uses the Benchmark.js library to time both methods on a nested array of integers, with the suite reporting each function’s operations per second. The recursive version, `flattenRecursive`, relies on `concat` and `forEach`, while the iterative `flatten` uses a `while` loop with `shift` to mutate the list in place. The output, logged via `console.log`, highlights the fastest method, demonstrating the performance trade-off between recursion and iteration.

AI-generated description

Similar vizzes