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

Simple example code sort 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 }

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

Your email address will not be published. Required fields are marked *