Reputation: 3158
This is my array:
let a = [
{
IsGroup: true,
Name: "Antonia Doyle"
},
{
IsGroup: false,
Name: "Dana Gray"
},
{
IsGroup: false,
Name: "Amber Banks"
},
{
IsGroup: false,
Name: "Geoff Neal"
},
{
IsGroup: true,
Name: "Nina Hartley"
},
{
IsGroup: false,
Name: "Elizabeth Warren"
},
{
IsGroup: false,
Name: "Ghengis Khan"
},
{
IsGroup: true,
Name: "Masta Razz"
}
];
I can't see to sort it by IsGroup
and then Name
. However, it doesn't seem to be working. My code so far:
let b = [];
b = a;
b.sort(byGroupThenName);
function byGroupThenName(a, b) {
return b.IsGroup - a.IsGroup || (a.Name - b.Name ? -1 : 1);
}
Upvotes: 0
Views: 60
Reputation: 1139
Use the dynamicSort()
function which takes two params property
and order
(asc
& desc
)
let a = [ { IsGroup: true , Name: "Antonia Doyle" },
{ IsGroup: false, Name: "Dana Gray" },
{ IsGroup: false, Name: "Amber Banks" },
{ IsGroup: false, Name: "Geoff Neal" },
{ IsGroup: true , Name: "Nina Hartley" },
{ IsGroup: false, Name: "Elizabeth Warren" },
{ IsGroup: false, Name: "Ghengis Khan" },
{ IsGroup: true , Name: "Masta Razz" } ]
const dynamicSort = (property, order) => {
let sortOrder = 1
if (order === 'desc') {
sortOrder = -1
}
return function(a, b) {
// a should come before b in the sorted order
if (a[property] < b[property]) {
return -1 * sortOrder
// a should come after b in the sorted order
} else if (a[property] > b[property]) {
return 1 * sortOrder
// a and b are the same
} else {
return 0 * sortOrder
}
}
}
const sortedArr = a.sort(dynamicSort('IsGroup','desc'))
console.log(sortedArr)
Upvotes: 2
Reputation: 22906
localeCompare
can be used to compare strings :
let arr = [ { IsGroup: true , Name: "Antonia Doyle" },
{ IsGroup: false, Name: "Dana Gray" },
{ IsGroup: false, Name: "Amber Banks" },
{ IsGroup: false, Name: "Geoff Neal" },
{ IsGroup: true , Name: "Nina Hartley" },
{ IsGroup: false, Name: "Elizabeth Warren" },
{ IsGroup: false, Name: "Ghengis Khan" },
{ IsGroup: true , Name: "Masta Razz" } ]
arr.sort((a, b) => b.IsGroup - a.IsGroup || a.Name.localeCompare(b.Name))
console.log( JSON.stringify(arr).replace(/},/g, '},\n ') )
Upvotes: 1