Reputation: 3229
I have an array of objects. each object has a "day type"; morning, afternoon, evening. They come in random order each time I get the list due to async differences... But I need to display them in following order: morning, afternoon, evening.
If I use array.sort() they will come out in order: afternoon, evening, morning. because it sorts alphabetically right?
So... I need a compare function. but I cant figure out how to make it since all examples I have found only has two input. sort(a, b)......
day.shifts = randomOrder;
day.shifts.sort((a, b, c) => {
//some how compare all 3
}
I hope this is possible, and it is probably piece of cake.... Other wise I have thought of solutions like so
day.shifts = randomOrder;
const morning = [];
const afternoon = [];
const evening = [];
day.shifts.forEach(shift => {
if(shift.type === 'morning'){
morning.push(shift)
}
if(shift.type === 'afternoon'){
afternoone.push(shift)
}
if(shift.type === 'evening'){
evening.push(shift)
}
}
day.shifts = morning.concat(afternoon).concat(evening);
I would prefer a compare method if that is possible. Or at least something a bit more "pretty" than my split to separate arrays and the concatenate method...
the objects in the list looks like this:
{
type: 'morning',
name: 'some person',
id: 'person db index',
}
Upvotes: 0
Views: 1103
Reputation: 386680
You could sort by type with an object for the order.
var types = { morning: 1, afternoon: 2, evening: 3 };
day.shifts.sort((a, b) => types[a.type] - types[b.type]);
Upvotes: 1
Reputation: 138437
You can sort them like this:
const order = ["morning", "afternoon", "evening"];
day.shifts.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type));
That basically sorts the shifts after wich type comes first in the order array.
Upvotes: 2