DEV Community

Discussion on: Flattening an Array, a Performance Test

Collapse
 
areddish profile image
Andrew

You could speed it up a little by counting and pre-allocating the array. Because that's going to be the slowest part of the classical for loop - the array allocations attributed to the pushes. Something like:

let size = 0;
for (let i = 0; i < initialArray.length; i++) {
  let current = initialArray[i];
  for (let j = 0; j < initialArray.length - 1; j++)
    size++;
}


let flattenedArray = new Array(size);
let k = 0;
for (let i = 0; i < initialArray.length; i++) {
  let current = initialArray[i];
  for (let j = 0; j < initialArray.length - 1; j++)
    flattenedArray[k] = current[j];
    k++;
}