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'.
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
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.
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
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:
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With