Reputation: 1754
I am first time playing with the React and I would like to sort data by column "Status", but not alphabetically, but with the specific order, let's say B, A, C and vice versa.
I have data as:
export interface Delivery {
id: number;
name: string;
amount: number;
status: string;
eta?: number;
}
export const getDeliveries = (): Promise<Delivery[]> => {
return new Promise((resolve) => {
setTimeout(() => {
const data = [
{
id: 1,
name: "Delivery 1",
amount: 3,
status: "A",
eta: 15
},
{
id: 2,
name: "Delivery 2",
amount: 5,
status: "C"
},
{
id: 3,
name: "Delivery 3",
amount: 3,
status: "A",
eta: 10
},
{
id: 4,
name: "Delivery 4",
amount: 4,
status: "B"
},
{
id: 5,
name: "Delivery 5",
amount: 3,
status: "A",
eta: 25
},
{
id: 6,
name: "Delivery 6",
amount: 3,
status: "C",
eta: 5
}
];
resolve(data);
}, 1000);
});
};
Thanks for any help or tip!
Upvotes: 0
Views: 615
Reputation: 1171
You could sort your data using the built-in Array.sort with a custom comparator.
const data = [{
id: 1,
name: "Delivery 1",
amount: 3,
status: "A",
eta: 15
},
{
id: 2,
name: "Delivery 2",
amount: 5,
status: "C"
},
{
id: 3,
name: "Delivery 3",
amount: 3,
status: "A",
eta: 10
},
{
id: 4,
name: "Delivery 4",
amount: 4,
status: "B"
},
{
id: 5,
name: "Delivery 5",
amount: 3,
status: "A",
eta: 25
},
{
id: 6,
name: "Delivery 6",
amount: 3,
status: "C",
eta: 5
}
];
const statusOrder = ["B", "A", "C"];
data.sort((d1, d2) => statusOrder.indexOf(d1.status) - statusOrder.indexOf(d2.status));
console.log(data);
Upvotes: 2