const 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]]]]]]]]]]] ]);
const flat = (argarr) => {
let arr = []
for (const item of argarr) {
if (Array.isArray(item)) arr = arr.concat(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]]]]]]]]]]] ]);
const flatten = (arr, acc = []) => {
arr.forEach(x => {
if (Array.isArray(x)) {
flatten(x, acc);
} else {
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]]]]]]]]]]] ]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for of | |
reduce TOC |
Test name | Executions per second |
---|---|
reduce | 111056.8 Ops/sec |
for of | 124577.1 Ops/sec |
reduce TOC | 140016.8 Ops/sec |
Measuring the performance of JavaScript microbenchmarks can be a complex task, but I'll break it down in a way that's easy to understand.
Benchmark Purpose
The provided benchmark measures the execution time of three different approaches for flattening an array with nested arrays. The goal is to determine which approach is the most efficient in terms of performance (measured in executions per second).
Approaches Compared
Array.prototype.reduce()
method to flatten the array. It iterates over each element, checks if it's an array, and recursively calls itself with the inner array.Pros and Cons
Library and Special JavaScript Features
In this benchmark, the Array.prototype.reduce()
method is used in all approaches. This is a built-in JavaScript method that reduces an array to a single value.
The For-of loop approach does not use any special JavaScript features beyond the standard for-of loop syntax.
Other Considerations
When measuring performance, it's essential to consider factors like:
Alternatives
Other approaches for flattening arrays include:
reduce()
or flat()
.Keep in mind that the performance differences between these approaches may vary depending on the specific use case, hardware, and JavaScript engine used.