var flatten = (arr) =>
arr.reduce((acc, x) => {
Array.isArray(x) ? flatten(x).forEach(y => acc.push(y)) : acc.push(x)
return acc;
}, [])
const x = flatten([ [1,2,3], [ [4,5,6], [7,8,9], [[[[[10,11,12]]], [13,14,15]]] ], [[[[[[[[[[[16,17,18]]]]]]]]]]] ]);
function flat(argarr) {
const arr = []
for (item of argarr) {
if (Array.isArray(item)) arr.push(flat(item))
else arr.push(item)
}
return arr
}
const x = flat([ [1,2,3], [ [4,5,6], [7,8,9], [[[[[10,11,12]]], [13,14,15]]] ], [[[[[[[[[[[16,17,18]]]]]]]]]]] ]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for of |
Test name | Executions per second |
---|---|
reduce | 201878.2 Ops/sec |
for of | 58945.7 Ops/sec |
Let's break down the provided JSON and benchmark explanation.
Benchmark Purpose
The benchmark tests two approaches to flatten an array: reduce
and for...of
. The goal is to compare their performance in flattening nested arrays.
Options Compared
Array.prototype.reduce()
method, which applies a function to each element of an array (in this case, the nested arrays) cumulatively, from left-to-right, so as to reduce it to a single output value.for
loop with the foreach
or of
keyword to iterate over the elements of the nested array.Pros and Cons
Library and Special JS Features
In this benchmark, there is no specific library used. However, note that Array.prototype.reduce()
is a built-in JavaScript method, which means it's not explicitly imported or required like in some other contexts.
There are no special JS features mentioned or tested in this benchmark.
Benchmark Preparation Code and Execution
The preparation code for each benchmark case is provided in the Benchmark Definition
section. The execution results are stored in the RawUAString
, Browser
, DevicePlatform
, OperatingSystem
, ExecutionsPerSecond
, and TestName
fields of the latest benchmark result.
Alternative Approaches
Other possible approaches to flatten a nested array could include:
flat()
Method (if available): Some modern browsers and environments support the Array.prototype.flat()
method, which can be used to flatten arrays in a single step.for
loops or other iteration mechanisms to iterate over the array elements.Keep in mind that each approach has its trade-offs in terms of readability, performance, and maintainability.