Q:

How to Sort an Array of Objects by Property Values in JavaScript

0

How to Sort an Array of Objects by Property Values in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the sort() Method

You can use the sort() method in combination with a custom comparison function to sort an array of JavaScript objects by property values. The default sort order is ascending.

The custom comparison function must return an integer equal to zero if both values are equal, an integer less than zero if the first value is less than the second value, and an integer greater than zero if the first value is greater than the second value.

The following example will show you how to sort an array of object by string property values.

// Defining comparison function 
function compareNames(a, b) {
    /* Converting name strings to lowercase to 
    ignore uppercase and lowercase in comparison */
    var nameA = a.name.toLowerCase();
    var nameB = b.name.toLowerCase();

    if(nameA < nameB) {
        return -1;
    }
    if(nameA > nameB) {
        return 1;
    }

    // Names must be equal
    return 0;
}


// Sample object array
var objArr = [ 
    { name: "Harry", age: 14 },
    { name: "Peter", age: 20 },
    { name: "Alice", age: 18 }
];


// Perform sorting
objArr.sort(compareNames);
console.log(objArr);

Defining comparison function for comparing numbers even much easier. To compare numbers instead of strings, the compare function can subtract b from a. Here's an example that shows how to sort an array of object by numeric property values in ascending order.

// Defining comparison function 
function compareAges(a, b) {
    return a.age - b.age;
}


// Sample object array
var objArr = [
    { name: "Harry", age: 14 },
    { name: "Peter", age: 20 },
    { name: "Alice", age: 18 }
];


// Perform sorting
objArr.sort(compareAges);
console.log(objArr);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Merge the Properties of Two JavaScript Obje... >>
<< How to Check If a Key Exists in a JavaScript Objec...