I want to sort my current array by having live at the front, instead of sorting it alphabetically so that the items with live will be at the front, followed by schedule and lastly end, but the way I'm doing it now with localeCompare, it will only sort alphabetically.
So how can I do so to sort the array in a specific way that I want?
Array Before Sorting Example
const [bulletins] = useState([
{
id: 1,
liveStatus: 'live',
},
{
id: 2,
liveStatus: 'live',
},
{
id: 3,
liveStatus: 'end',
},
{
id: 4,
liveStatus: 'schedule',
},
{
id: 5,
liveStatus: 'end',
}
]);
Sorted Array Example
const [bulletins] = useState([
{
id: 3,
liveStatus: 'end',
},
{
id: 5,
liveStatus: 'end',
},
{
id: 2,
liveStatus: 'live',
},
{
id: 1,
liveStatus: 'live',
},
{
id: 4,
liveStatus: 'schedule',
}
]);
const displayBulletins = bulletins
.sort((a,b) => {
return a.liveStatus.localeCompare(b.liveStatus)
})
.map((bulletin) => {
return (
<Fragment key={bulletin.id}>
<BulletinList
bulletin={bulletin}
/>
</Fragment>
);
})
You can use indexOf to check the first letter in a list of sorted letters ('lse' in this case):
const bulletins = [{id: 1,liveStatus: 'live',},{id: 2,liveStatus: 'live',},{id: 3,liveStatus: 'end',},{id: 4,liveStatus: 'schedule',},{id: 5,liveStatus: 'end',}];
bulletins.sort((a, b) => 'lse'.indexOf(a.liveStatus[0]) - 'lse'.indexOf(b.liveStatus[0]));
console.log(bulletins);
Then no need to sort the elements, all you can use is reduce and arrange in the way you like
const arr = [
{
id: 1,
liveStatus: "live",
},
{
id: 2,
liveStatus: "live",
},
{
id: 3,
liveStatus: "end",
},
{
id: 4,
liveStatus: "schedule",
},
{
id: 5,
liveStatus: "end",
},
];
const dict = { live: 0, schedule: 1, end: 2 };
const resultObj = Array.from({ length: Object.keys(dict).length + 1 }, () => []);
const result = arr
.reduce((acc, curr) => {
acc[dict[curr.liveStatus] ?? resultObj.length - 1].push(curr);
return acc;
}, resultObj)
.flat();
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}