Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array first by boolean column then by string column

I'm trying to so sort an array by 2 fields. I have a boolean: isFavorite and a string: name. All the booleans who are true have to be the first items. But I want the array to be alphabetic. This is my code so far (tried multiple things):

data.sort(function (x,y) {
    if (x.isFavorite){
        return -1;
    }
    if (x.isFavorite && !y.isFavorite && (x.name < y.name)){
        return -1;
    }  else if ((x.isFavorite === y.isFavorite) && (x.name === y.name)){
        return 0;
    } else if (x.isFavorite && y.isFavorite && (x.name < y.name)){
        return -1;
    } else if (!x.isFavorite && !y.isFavorite && (x.name > y.name)){
        return 1;
    }
}
like image 366
Pieter Avatar asked Dec 21 '17 08:12

Pieter


2 Answers

Why so much conditions and overlapping ?

Just use logical OR operator in order to sort array by two fields.

Also, I used + (Boolean) in order to force converting to Number.

grouperArray.sort((a, b) => (+a.isFavorite) - (+b.isFavorite) || a.name.localeCompare(b.name));

let data = [{ isFavorite:false, name:'A' }, { isFavorite:true, name:'C' }, { isFavorite:true, name:'B' }];
data.sort((a,b) => (+b.isFavorite) - (+a.isFavorite) || a.name.localeCompare(b.name));
console.log(data);
like image 53
Mihai Alexandru-Ionut Avatar answered Nov 15 '22 08:11

Mihai Alexandru-Ionut


const data = [
  {isFavorite: false, name: 'b'},
  {isFavorite: false, name: 'f'},
  {isFavorite: true, name: 'c'},
  {isFavorite: true, name: 'a'},
  {isFavorite: false, name: 'd'},
  {isFavorite: true, name: 'g'}
];

const sortedData = data.sort((a, b) => {
  if (a.isFavorite !== b.isFavorite) {
    return a.isFavorite ? -1 : 1;
  } else {
    return a.name > b.name ? 1 : -1;
  }
});
  
console.log(sortedData);
like image 36
klugjo Avatar answered Nov 15 '22 08:11

klugjo