6

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'.

2 Answers 2

13

You 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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Elegant way to do it.
This was exactly what I was looking for, thanks! I noticed a few other responses to this question originally that were less elegant but after seeing this solution they must have removed their posts. Either way, this was not only a good and efficient solution, but your answer was very thorough thanks to the use of mock data. Props to you sir/madame!
doesn't work for me. It says that boolean cannot be converted to number.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.