Sort an array to have specific items first in the array

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.

Leave a Comment