Sort an array to have specific items first in the array
A simpler and more elegant way to do is by building a new array by filtering the old one twice: once filtered by flag: true
and once by flag: false
. All together it would look like:
// THE INITIAL ARRAY:
const originalArray = [
{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}
];
// THE SORTED ARRAY:
const sortedArray = [
...originalArray.filter(({flag}) => flag),
...originalArray.filter(({flag}) => !flag)
];
In my opinion it is way easier for a human to read than using comparer or reducer functions, and (based on measurements) it is also a pretty well-performing solution.
A performance comparison:
I saw that the most upvoted answer using arr.reduce()
performs around 20x slower than this solution. I used ES6 Console for comparison, feel free to test it yourself too!
Measuring the array.reduce()
way:
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 }
];
// Lets multiple the array items 11 times to increase the looping process:
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
Measuring the array.filter()
way:
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 }
];
// Lets multiple the array items 11 times to increase the looping process:
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
The Spread syntax introduced with ECMAScript6 (e.g., [...object]
) makes this relatively straightforward using an Array's reduce
method:
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 }
];
const sortedArr = arr.reduce((acc, element) => {
if (!element.flag) {
return [element, ...acc];
}
return [...acc, element];
}, []);
I found this example of extended parameter handling really helpful.