Skip to content

Instantly share code, notes, and snippets.

@pcnate
Created December 5, 2018 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcnate/30be6ba188897816ae47a33bd441bb27 to your computer and use it in GitHub Desktop.
Save pcnate/30be6ba188897816ae47a33bd441bb27 to your computer and use it in GitHub Desktop.
flatten an array of objects with a property that contains an array
const arr = [
{ sub: [ 1001, 1002, 1003, 1004, 1005 ] },
{ sub: [ 2001, 2002, 2003, 2004, 2005 ] },
{ sub: [ 3001, 3002, 3003, 3004, 3005 ] },
{ sub: [ 4001, 4002, 4003, 4004, 4005 ] },
{ sub: [ 5001, 5002, 5003, 5004, 5005 ] },
];
const startDates = [];
const endDates = [];
const commands = [];
results = [];
const cycles = 1000000;
console.log( 'running [].concat( ...arr.map( x => x.sub ))', cycles, 'times' );
commands.push( '[].concat( ...arr.map( x => x.sub ))' );
startDates.push( new Date().getTime() );
for( let index = 0; index < cycles; index++ ) {
[].concat( ...arr.map( x => x.sub ));
}
endDates.push( new Date().getTime() );
console.log( 'running arr.forEach( x => x.sub.forEach( y => res.push( y ) ) )', cycles, 'times' );
commands.push( 'arr.forEach( x => x.sub.forEach( y => res.push( y ) ) )' );
startDates.push( new Date().getTime() );
for( let index = 0; index < cycles; index++ ) {
let res = [];
arr.forEach( x => x.sub.forEach( y => res.push( y ) ) );
}
endDates.push( new Date().getTime() );
for (let index = 0; index < startDates.length; index++) {
console.log( cycles + 'x ' + (endDates[index] - startDates[index]) + 'ms ' + commands[index] );
}
@pcnate
Copy link
Author

pcnate commented Dec 5, 2018

1000000x   407ms       [].concat( ...arr.map( x => x.sub ))
1000000x   158ms       arr.forEach( x => x.sub.forEach( y => res.push( y ) ) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment