javascript - Sorting objects based on a string value property in TypeScript - Stack Overflow

I have an array of objects and the definition for an object looks something like this:export class Acco

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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);
});

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743716704a4495110.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信