Skip to content

Instantly share code, notes, and snippets.

@vanling
Created September 9, 2020 06:28
Show Gist options
  • Save vanling/d1eaba6aaedca5a27950d1c77aff0aa1 to your computer and use it in GitHub Desktop.
Save vanling/d1eaba6aaedca5a27950d1c77aff0aa1 to your computer and use it in GitHub Desktop.
Javascript - Sorting on two (specific) types (slow & fast)
//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