'Sort object based on Enum List
I have an Object with multiple properties and want to sort based on specific enum list.
Below is Object
const ArratOfobj = [
{ id: 3, ShortType: "LocationWorn", ImageType: "B" },
{ id: 2, ShortType: "SipStillLife", ImageType: "D" },
{ id: 1, ShortType: "SipStillWorn", ImageType: "M" },
{ id: 4, ShortType: "LocationLife", ImageType: "M" },
];
Enum Order
const order= {
'0': { ShortType: "SIP Still Life", ImageType: "M"},
'1': { ShortType: "SIP Still Life", ImageType: "B" },
'2': { ShortType: "Location Still Life", ImageType: "M" },
'3': { ShortType: "Location Still Life", ImageType: "B" }
}
**Expected Output **
[
{ id: 2, ImageType: "D", ShortType: "SipStillLife" },
{ id: 4, ImageType: "M", ShortType: "LocationLife" },
{ id: 1, ImageType: "M", ShortType: "SipStillWorn" },
{ id: 3, ImageType: "B", ShortType: "LocationWorn" }
]
Solution 1:[1]
you can't create an object by this way, but I guess you meant an array ob objects.
there is how you could sort this array by using enum order :
const ArratOfobj = [
{ id: 3, ShortType: "LocationWorn", ImageType: "B" },
{ id: 2, ShortType: "SipStillLife", ImageType: "D" },
{ id: 1, ShortType: "SipStillWorn", ImageType: "M" },
{ id: 4, ShortType: "LocationLife", ImageType: "M" },
];
const enum Order {
SipStillLife = 0,
LocationLife = 1,
SipStillWorn = 2,
LocationWorn = 3,
}
const sortedArray = ArratOfobj.sort((a, b) => {
return Order[a.ShortType] - Order[b.ShortType];
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chadjaa Sofianne |
