0

I have an array of table rows that need to be sorted by the field "data" ascending.

var data = [
  {data: 5},
  {data: 10, sticky: true},
  {data: 90},
  {data: 50, sticky: true},
  {data: 20, sticky: true},
  {data: 70},
];

But there is a catch. I need rows with the "sticky" flag to be sorted to the top of the table. My sort function currently looks like this:

data.sort(function(a, b) {
   if (a.sticky) return -1;
   if (b.sticky) return +1;
   return mySortFunction(a, b);
});

which yields

[
  {data: 10, sticky: true},
  {data: 50, sticky: true},
  {data: 20, sticky: true},
  {data: 5},
  {data: 70},
  {data: 90}
]

The problem is, I need the "sticky" rows to be sorted by "data" (asc) as well. Is there an easy way to do that without splitting the data into a sticky and non-sticky group first and then running the sortfunction against both groups?

Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44
  • 1
    https://stackoverflow.com/questions/4576714/sort-by-two-values-prioritizing-on-one-of-them – mplungjan Aug 21 '17 at 11:44
  • 2
    @mplungjan, thank you but I don't think this is the same question. In the suggested thread all rows have an alternative property to sort by. In my example only a few rows have the sticky property. Maybe I'm just not getting it. Can you post a code example using my data? – Đinh Carabus Aug 21 '17 at 11:52
  • 1
    `data.sort((a,b)=>!!b.sticky-!!a.sticky||a.data-b.data)` (the question @mplungjan refs has infered this clearly) – user943702 Aug 21 '17 at 11:59
  • @user943702 thanks, I think it's clearer to me now. – Đinh Carabus Aug 21 '17 at 12:08

1 Answers1

3

You can do something like this:

var data = [
    {data: 5},
    {data: 10, sticky: true},
    {data: 90},
    {data: 50, sticky: true},
    {data: 20, sticky: true},
    {data: 70},
];

function mySortFunction(a, b) {
    return a.data - b.data;
}

function sort(a, b) {
    if(a.sticky === b.sticky) {
        return mySortFunction(a, b);
    } else if (a.sticky){
        return -1;
    }
    // b.sticky === true
    return 1;
}

console.log(data.sort(sort));
Vadim
  • 8,701
  • 4
  • 43
  • 50