Sunday, October 8, 2017

Sample program to sort an array of objects by its property value using JavaScript

Assume we have an object and we want to sort it based on it's property. We can utilize the JavaScript sort method to achieve this. The property value can be string or integer.

var items = [
    { firstname: 'Lazslo', lastname: 'Jamf',  accountType: 'Gold', age: 25},
    { firstname: 'Barack', lastname: 'Obamo',  accountType: 'Platinum', age: 45 },
    { firstname: 'Pig',    lastname: 'Bodine',  accountType: 'Silver', age: 36},
    { firstname: 'Pirate', lastname: 'Prentice',  accountType: 'Platinum', age: 29 }
];

Using the below function it it will be sorted by the 'accountType' string property.

items.sort(function(a, b) {
    var x = a.accountType.toLowerCase(), y = b.accountType.toLowerCase();
    return x < y ? -1 : x > y ? 1 : 0;
});

If we want to sort by the integer property 'age' means use the below method,


items.sort(function(a, b) {
     return a.age - b.age;
});

No comments:

Post a Comment