<!--your preparation HTML code goes here-->
var arr = [];
var size = 1000;
var size_n = 100;
for (let i = 0; i < size; i++) {
const innerData = [];
for (let j = 0; j < 2; j++) { // Still 2 sub-arrays per data
const subArray = [];
for (let k = 0; k < size_n; k++) {
subArray.push(i * size_n + j * size_n + k); // Unique values
}
innerData.push(subArray);
}
arr.push({
data: innerData
});
}
var result = [];
for (let i = 0; i < arr.length; i++) {
const data = arr[i].data;
for (let j = 0; j < data.length; j++) {
const subArray = data[j];
for (let k = 0; k < subArray.length; k++) {
result.push(subArray[k]);
}
}
}
var result = [];
for (let item of arr) {
for (let subArray of item.data) {
for (let element of subArray) {
result.push(element);
}
}
}
arr.flatMap(x => x.data).flat()
arr.map(x => x.data).flat(2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for of | |
flatMap | |
flatMap(n) |
Test name | Executions per second |
---|---|
for | 955.3 Ops/sec |
for of | 811.4 Ops/sec |
flatMap | 369.5 Ops/sec |
flatMap(n) | 365.1 Ops/sec |
The benchmark represents a performance comparison of different iteration methods available in JavaScript for traversing a two-dimensional array. Specifically, it evaluates the “for” loop, the “for..of” loop, and various usage of the flatMap
method to flatten nested arrays.
For Loop
var result = [];
for (let i = 0; i < arr.length; i++) {
const data = arr[i].data;
for (let j = 0; j < data.length; j++) {
const subArray = data[j];
for (let k = 0; k < subArray.length; k++) {
result.push(subArray[k]);
}
}
}
For..Of Loop
var result = [];
for (let item of arr) {
for (let subArray of item.data) {
for (let element of subArray) {
result.push(element);
}
}
}
FlatMap
arr.flatMap(x => x.data).flat();
FlatMap with a depth argument
arr.map(x => x.data).flat(2);
flatMap
while allowing control over how deep the flattening goes.The benchmark results indicated:
for
loop might be preferred. However, for code readability and maintainability in moderate-sized data, using for..of
or flatMap
might be sufficient.map
and reduce
methods for transforming and accumulating values.forEach
for simpler iteration, though this can be less performant compared to for loops.In sum, different scenarios dictate the best approach for array iteration and flattening in JavaScript, and engineers should gauge their choice against performance needs, readability, and data complexity.