Skip to content

JavaScript sort by property | Array Object

  • by

Use the sort() method to sort Array objects by property in JavaScript. The sort() method sorts its elements according to the values returned by a custom sort function.

sort(function compareFn(a, b) { /* ... */ })
compareFunction(a, b) return valuesort order
> 0sort a after b
< 0sort a before b
=== 0keep original order of a and b

By default, the sort() method logically sorts the given data type.

JavaScript sort by property

A simple example code sorts an array of objects based on the values of the object’s properties.

Let’s sort the elements of an array alphabetically and not numerically.

<!DOCTYPE html>
<html>
<body>
  <script>
    function compareName(a, b) {

    // converting to uppercase to have case-insensitive comparison
    const name1 = a.name.toUpperCase();
    const name2 = b.name.toUpperCase();

    let comparison = 0;

    if (name1 > name2) {
      comparison = 1;
    } else if (name1 < name2) {
      comparison = -1;
    }
    return comparison;
  }

  const students = [{name: 'XYZ', age:300},{name: 'ABC', age:200}, {name: 'PQR', age:100}];

  console.log(students.sort(compareName));
</script>
</body>
</html>

Output:

JavaScript sort by property Array Object

Sort Array by Property by numeric values

<script>
    function compareAge(a, b) {

      return a.age - b.age;
    }

    const students = [{name: 'XYZ', age:300},{name: 'ABC', age:200}, {name: 'PQR', age:100}];

    console.log(students.sort(compareAge));
</script>

Output:

0: Object { name: "PQR", age: 100 }

1: Object { name: "ABC", age: 200 }

2: Object { name: "XYZ", age: 300 }

To sort in descending order, you can reverse the subtraction:

array.sort((a, b) => {
    return b.age - a.age;
});

You can also sort by other properties, such as name. For example, sorting alphabetically by name:

array.sort((a, b) => {
    if (a.name < b.name) {
        return -1;
    }
    if (a.name > b.name) {
        return 1;
    }
    return 0;
});

This comparison function uses string comparison to sort the objects by the name property in ascending order. For descending order, you can swap the comparison:

array.sort((a, b) => {
    if (a.name < b.name) {
        return 1;
    }
    if (a.name > b.name) {
        return -1;
    }
    return 0;
});
array.sort((a, b) => {
    if (a.name < b.name) {
        return 1;
    }
    if (a.name > b.name) {
        return -1;
    }
    return 0;
});

By using these techniques, you can sort an array of objects by any property in either ascending or descending order.

Do comment if you have any doubts or suggestions on this JS sorting object code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading