In order to sort an array of objects by a specific property with the following criteria: - The first item must be either Camel or Absolute. - The second item must be Dream. - The third item must be Carnival.
[Camel, Dream, Carnival] or [Absolute, Dream, Carnival]
For Example 1:
var items = [
{ 'Name':'Carnival', 'TypeId':3, ... },
{ 'Name':'Camel', 'TypeId':55, ... },
{ 'Name':'Dream', 'TypeId':4 , ...},
]
The expected result is:
var itemsSorted = [{ 'Name':'Camel', 'TypeId':55, ... },
{ 'Name':'Dream', 'TypeId':4, ... },
{ 'Name':'Carnival', 'TypeId':3, ... }]
For Example 2:
var items = [
{ 'Name':'Carnival', 'TypeId':3, ... },
{ 'Name':'Dream', 'TypeId':4 , ...},
{ 'Name':'Absolute', 'TypeId':114 , ...}]
The expected result is:
var itemsSorted = [{ 'Name':'Absolute', 'TypeId':114, ... },
{ 'Name':'Dream', 'TypeId':4, ... },
{ 'Name':'Carnival', 'TypeId':3, ... }]
I have implemented a solution that works based on these criteria. However, I am open to suggestions for a more elegant approach. Any recommendations?
private _setUpdateProgress() {
const order = ['Camel', 'Absolute', 'Dream', 'Carnival'];
this.itemsSorted = [];
if (this.items?.length) {
for (let i = 0; i < order.length; i++) {
if (i === 1) {
continue;
}
let info!: Array<any>;
if (i === 0) {
info = items.filter(x => x.Name ===
order[0] || x.Name === order[1]);
}
if (i > 1) {
info = items.filter(x => x.Name===
order[i]);
}
this.itemsSorted.push(info[0]);
}
}