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;
}
}
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With