mc_convertArray2Dto1D

Benchmark created on


Description

// need to convert a 2D array to a 1D array // треба перетворити 2Д масив на 1Д масив // [[1, 2], [3, 4], [5, 6]] => [ 1, 2, 3, 4, 5, 6 ]

Setup

const nums = new Array(100).fill(0).map(() => new Array(100).fill(0));

Test runner

Ready to run.

Testing in
TestOps/sec
bad1a
const bad1a = nums.reduce((acc, row) => [...acc, ...row], []);
ready
bad1b
const bad1b = nums.reduce((acc, row) => {
  row.forEach(el => acc.push(el));
  return acc;
}, []);
ready
bad1c
const bad1c = nums.reduce((acc, row) => {
  acc.push(...row);
  return acc;
}, []);
ready
bad2a
let bad2a = [];
nums.forEach((arr) => bad2a = bad2a.concat(arr));
ready
bad2b
let bad2b = [];
for (let row = 0; row < nums.length; row++) {
  bad2b = bad2b.concat(nums[row]);
}
ready
bad3
const bad3 = JSON.parse("[" + JSON.stringify(nums).replace(/\[|\]/g, "") + "]");
ready
good1a
const good1a = nums.flat();
ready
good1b
const good1b = nums.flatMap(row => row);
ready
good2a
const good2a = [];
nums.forEach((arr) => good2a.push(...arr));
ready
good2b
const good2b = [];
for (let row = 0; row < nums.length; row++) {
  good2b.push(...nums[row]);
}
ready
good3a
const good3a = [];
for (let row = 0; row < nums.length; row++) {
  for (let col = 0; col < nums[0].length; col++) {
    good3a.push(nums[row][col]);
  }
}
ready
good3b
const good3b = new Array(nums.length * nums[0].length);
let ind = 0;
for (let row = 0; row < nums.length; row++) {
  for (let col = 0; col < nums[0].length; col++) {
    good3b[ind] = nums[row][col];
    ind++
  }
}
ready
good4a
const good4a = [].concat.apply([], nums);
ready
good4b
const good4b = [].concat(...nums);
ready
good4c
const good4c = Array.prototype.concat.call([], ...nums);
ready
good5
const good5 = [];
nums.forEach(row => Array.prototype.push.apply(good5, row));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.