简体   繁体   中英

javascript sort, Compare 3 different types and sort in order

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',
}

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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM