Created
September 9, 2020 06:28
-
-
Save vanling/d1eaba6aaedca5a27950d1c77aff0aa1 to your computer and use it in GitHub Desktop.
Javascript - Sorting on two (specific) types (slow & fast)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SLOW | |
const arr = [ | |
{ flag: true, other: 1 }, | |
{ flag: true, other: 2 }, | |
{ flag: false, other: 3 }, | |
{ flag: true, other: 4 }, | |
{ flag: true, other: 5 }, | |
{ flag: true, other: 6 }, | |
{ flag: false, other: 7 } | |
]; | |
new Array(11).fill().forEach(x => arr.push(...arr)); | |
console.time(); | |
const reducedArr = arr.reduce((acc, element) => { | |
if (element.flag === false) { | |
return [element, ...acc]; | |
} | |
return [...acc, element]; | |
}, []); | |
console.timeEnd(); // RESULTS: between 285-350ms | |
//FAST | |
const arr = [ | |
{ flag: true, other: 1 }, | |
{ flag: true, other: 2 }, | |
{ flag: false, other: 3 }, | |
{ flag: true, other: 4 }, | |
{ flag: true, other: 5 }, | |
{ flag: true, other: 6 }, | |
{ flag: false, other: 7 } | |
]; | |
new Array(11).fill().forEach(x => arr.push(...arr)); | |
console.time(); | |
const rebuiltArray = [ | |
...arr.filter(x => !!x.flag), | |
...arr.filter(x => !x.flag) | |
]; | |
console.timeEnd(); // RESULTS: between 6-20ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment