I've implement this sort:
<tbody>
{results.sort((a, b) => a.status > b.status ? 1 : -1).map(el => {
return (
<tr>
<td>{el.id}</td>
<td>{el.amount}</td>
<td>{el.time}</td>
<td>{el.status}</td>
</tr>
);
})}
</tbody>
So now I have them sorted by status as follows: active, updated, waiting. The problem is that I want them sorted by active, waiting, updated. How can I achieve this?
This is my array of objects:
const data = [
{
id: 1,
title: "Order 1",
amount: 3,
status: "active"
},
{
id: 2,
title: "Order 2",
amount: 5,
status: "waiting"
},
{
id: 3,
title: "Order 3",
amount: 4,
status: "updated"
},
{
id: 4,
title: "Order 4",
amount: 3,
status: "active"
}
];
CodePudding user response:
You can use indexOf
to an ordered array, with this approach:
const data = [{
id: 1,
title: "Order 1",
amount: 3,
status: "active"
},
{
id: 2,
title: "Order 2",
amount: 5,
status: "waiting"
},
{
id: 3,
title: "Order 3",
amount: 4,
status: "updated"
},
{
id: 4,
title: "Order 4",
amount: 3,
status: "active"
}
];
const statusOrdered = ['active', 'waiting', 'updated']
data.sort((a, b) => statusOrdered.indexOf(a.status) - statusOrdered.indexOf(b.status));
console.log(data)
CodePudding user response:
Try something like this for your sorting function.
(a,b) => {
let ranking = {
active:1,
waiting:2,
updated:3,
}
return ranking[a.status] - ranking[b.status]
}