I have an array of objects and the definition for an object looks something like this:
export class AccountInfo {
accountUid: string;
userType: string;
firstName: string;
middleName: string;
lastName: string;
}
NOTE: The reason I don't have userType as an enum is because the object is populated by a database call and I couldn't figure out a clean way to have the string returned from the db populate the enum.
I want to sort the array so that objects with a userType of 'STAFF' appear first, followed by 'TEACHER', then 'PARENT', then 'STUDENT'.
I have an array of objects and the definition for an object looks something like this:
export class AccountInfo {
accountUid: string;
userType: string;
firstName: string;
middleName: string;
lastName: string;
}
NOTE: The reason I don't have userType as an enum is because the object is populated by a database call and I couldn't figure out a clean way to have the string returned from the db populate the enum.
I want to sort the array so that objects with a userType of 'STAFF' appear first, followed by 'TEACHER', then 'PARENT', then 'STUDENT'.
Share Improve this question asked Apr 22, 2017 at 21:26 TovrikTheThirdTovrikTheThird 5112 gold badges7 silver badges23 bronze badges2 Answers
Reset to default 13You can store the order in an array
, then just use indexOf
with sort
to achieve your goal. See the code example below:
const humans = [{
accountUid: "1",
userType: "TEACHER",
}, {
accountUid: "2",
userType: "STAFF",
}, {
accountUid: "3",
userType: "STUDENT",
}, {
accountUid: "4",
userType: "PARENT",
}];
const order = ['STAFF', 'TEACHER', 'PARENT', 'STUDENT'];
const result = humans.sort((a, b) => order.indexOf(a.userType) - order.indexOf(b.userType));
console.log(result)
If you can't use ES6, just use:
humans.sort(function(a, b){
return order.indexOf(a.userType) - order.indexOf(b.userType);
});
Here is another way to do it, probably have an order object to store the orders
const actionOrder = {
"EAT" : 1,
"SLEEP" : 2,
"PLAY" : 3,
} as const;
const users = [{
name: "Mike",
action: "PLAY"
}, {
name: "John",
action: "EAT"
}, {
name: "Harry",
action: "SLEEP"
}
];
users.sort((a,b) => {
return actionOrder[a.action] - actionOrder[b.action];
});
console.log(users);