I need to sort an object array based on the status in angular 16+. My status order should be [N-Op, Used, Unknown, Op]
Sample object :
const stockList = [
{
'heading': 'SK',
'status': 'N-Op',
},
{
'heading': 'SKU',
'status': 'Op',
},
{
'heading': 'Uniliver',
'status': 'Op',
},
{
'heading': 'Bugati',
'status': 'Unknown',
},
{
'heading': 'Bugati',
'status': 'N-Op',
},
];
How could I achieve the expected result as below.
const stockList = [
{
'heading': 'SK',
'status': 'N-Op',
},
{
'heading': 'Bugati',
'status': 'N-Op',
},
{
'heading': 'Bugati',
'status': 'Unknown',
},
{
'heading': 'SKU',
'status': 'Op',
},
{
'heading': 'Uniliver',
'status': 'Op',
}
];
>Solution :
You should work with Array.prototype.sort() and defining the custom logic to compare the index from the sortOrder array.
Assume that all values of status existed in sortOrder array.
const sortOrder = ["N-Op", "Used", "Unknown", "Op"];
let sortedStockList = stockList.sort((a, b) => {
let xIndex = sortOrder.indexOf(a.status);
let yIndex = sortOrder.indexOf(b.status);
if (xIndex < yIndex)
return -1;
else if (xIndex > yIndex)
return 1;
else
return 0;
});
(Optional) If you want the sort followed by heading, you can replace return 0; with
return a.heading.localeCompare(b.heading);