Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting objects based on a string value property in TypeScript

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

like image 794
TovrikTheThird Avatar asked Apr 22 '17 21:04

TovrikTheThird


People also ask

How to sort an array of objects in JavaScript?

order an array object by a property of the object in javascript sort an array of objects by property alphabetically javascript sort the array of object with respect to attribute in typescript sort array of objects javascript with value number of string sort array of objects by different string property value in javascript

Can We sort data by the value of a string property?

We can sort and filter data on various conditions, and sorting by the value of a string property is a common one. For example, suppose we have a list of students with their firstName and lastName: We could sort these students by either their firstName or lastName.

How to sort array of objects on ascending order with id property?

Let’s declare an array of objects where each object holds id and name properties Following is an example of Sorting array of objects on ascending order with id property Lodash library provides many utilities functions. sortBy is one of the method for sorting an array. First, install lodash npm or include lodash cdn library into your application

How to alphabetically sort an array of strings in Python?

Let’s start with the most basic example and sort the array of strings: const words = ['Tango', 'Zulu', 'Bravo', 'Lima']; words.sort (); // -> ['Bravo', 'Lima', 'Tango', 'Zulu'] That’s the simplest way to alphabetically sort an array of strings in ascending order. What if we want to sort it from Z to A instead? We need to pass a compare function:


1 Answers

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);
});
like image 157
Dan Cantir Avatar answered Oct 17 '22 01:10

Dan Cantir