Javascript sort array of objects by property

This article will discuss how to sort an array of objects based on the values of the object’s properties.

In JavaScript, we use the sort() function to sort an array of objects. The sort() function is used to sort the elements of an array alphabetically and not numerically. To get the items in reverse order, we may use the reverse() method.

However, the traditional sort() function may lag behind at times to compare an array of objects based on some property. So we can create a user-defined compare function to be used with the sort() function. This method compares the properties of the items in an array.

The example below shows how to write your own comparison function.

let students = [
    {
        fname : "Rohan",
        lname : "Dalal",
        age : 19
    },

    {
        fname : "Zain",
        lname : "Ahmed",
        age : 17
    },

    {
        fname : "Anadi",
        lname : "Malhotra",
        age : 19
    }
];


function compare_lname( a, b )
  {
  if ( a.lname.toLowerCase() < b.lname.toLowerCase()){
    return -1;
  }
  if ( a.lname.toLowerCase() > b.lname.toLowerCase()){
    return 1;
  }
  return 0;
}

students.sort(compare_lname);
console.log(students)

Output:

[
  { fname: 'Zain', lname: 'Ahmed', age: 17 },
  { fname: 'Rohan', lname: 'Dalal', age: 19 },
  { fname: 'Anadi', lname: 'Malhotra', age: 19 }
]

In the above example, first, convert the lname to lowercase and then we compare the names depending on the string comparison. It returns the sorted array of objects based on the lname of the object. For descending order, we can replace the sort() function with reverse().

If we are dealing with strings, we can eliminate the need to create a compare function and simply use the localeCompare() function with the sort() function to get the desired result.

See the code below.

let students = [
    {
        fname : "Rohan",
        lname : "Dalal",
        age : 19
    },

    {
        fname : "Zain",
        lname : "Ahmed",
        age : 21
    },

    {
        fname : "Anadi",
        lname : "Malhotra",
        age : 16
    }
];


students.sort((a, b) => a.lname.localeCompare(b.lname));
console.log(students);

Output:

[
  { fname: 'Zain', lname: 'Ahmed', age: 21 },
  { fname: 'Rohan', lname: 'Dalal', age: 19 },
  { fname: 'Anadi', lname: 'Malhotra', age: 16 }
]

The localeCompare() works only for strings. We cannot use this for numbers.

To get the sorted array based on some numerical property, we have to provide some compare function in the sort() method because the sort() method normally also does not work with numbers.

See the code below.

let students = [
    {
        fname : "Rohan",
        lname : "Dalal",
        age : 19
    },

    {
        fname : "Zain",
        lname : "Ahmed",
        age : 21
    },

    {
        fname : "Anadi",
        lname : "Malhotra",
        age : 16
    }
];

students.sort((a, b) => {
    return a.age - b.age;
});
console.log(students);

The above example compares the age of the objects and sorts them based on this age. The compare function is only a single line, so it is provided directly with the sort() method. To get everything in descending order, use the reverse() function.

Alternatively, we can also shift the order in the compare function to get the final output in descending order.

For example,

let students = [
    {
        fname : "Rohan",
        lname : "Dalal",
        age : 19
    },

    {
        fname : "Zain",
        lname : "Ahmed",
        age : 21
    },

    {
        fname : "Anadi",
        lname : "Malhotra",
        age : 16
    }
];

students.sort((a, b) => {
    return b.age - a.age;
});
console.log(students);

Output:

[
  { fname: 'Zain', lname: 'Ahmed', age: 21 },
  { fname: 'Rohan', lname: 'Dalal', age: 19 },
  { fname: 'Anadi', lname: 'Malhotra', age: 16 }
]


The given task is to sort an array of objects by using string property value in JavaScript.

Assume there is an array of objects and we need to sort those elements by using the string property. In this below scenario, we are sorting array of objects by "company" property.

const array = [ {Company: 'Oneplus', Manufacturing: 'China'}, {Company: 'Samsung', Manufacturing: 'South korea'}, {Company: 'Nothing', Manufacturing: 'India'} ]; Output = [ {"Company":"Nothing","Manufacturing":"India"}, {"Company":"Oneplus","Manufacturing":"China"}, {"Company":"Samsung","Manufacturing":"South korea"} ]

We can achieve this task, sorting of array objects by string property value by using sort() method and compare() function.

Sort()

The sort() method sorts all the elements in array object and will return the sorted array. it'll sort in ascending order by default.

Syntax

Following is the syntax of sort() method −

Array.sort();

Compare function

The compare function will return negative, zero or positive values, depending upon the arguments.

The syntax of compare function will be,

function(a, b){return a - b}

Note − The sort() function compares two values, sends the results to the compare function, and then sorts the output based on the result.

  • a will be sorted before b, if the outcome is Negative.

  • if it is 0 (zero), none happens.

  • b will be sorted before a, if the outcome is positive.

Here if we want to sort the array objects by string property value, we need to use sort() method which will sort all the array elements and the compare function, when we passed as an argument into the sort() method, it will define the sorting order and the sorting pattern.

Example 1

Sorted in ascending order

Following is an example where an array of objects has been sorted by using string property value −

<!DOCTYPE html> <html> <head> <title>Sort array of objects by string property value</title> </head> <body> <button onClick="fun()"> Click to sort </button> <p id="para"></p> <script> function fun() { function func( object1, object2 ){ if (object1.Company < object2.Company) return -1; if (object1.Company > object2.Company) return 1; return 0; } const array = [ {Company: 'Oneplus', Manufacturing: 'China'}, {Company: 'Samsung', Manufacturing: 'South korea'}, {Company: 'Nothing', Manufacturing: 'India'} ]; array.sort(func); document.getElementById("para").innerHTML = "After sorting "Company" in ascending order: " + JSON.stringify(array); }; </script> </body> </html>

As we can see the output, we have used sort() method to sort the array object properties by string value. We have passed the compare() function as an argument of the sort() method to sort the company in ascending order.

Example 2

Sorted in descending order

Following is an example to sort array of objects by using string property value in descending order.

<!DOCTYPE html> <html> <head> <title>Sort array of objects by string property value</title> </head> <body> <button onClick="fun()"> Click to sort </button> <p id="para"></p> <script> function fun() { function func( object1, object2 ){ if (object1.Manufacturing < object2.Manufacturing) return -1; if (object1.Manufacturing > object2.Manufacturing) return 1; return 0; } var array = [ {Company: 'Oneplus', Manufacturing: 'China'}, {Company: 'Samsung', Manufacturing: 'South korea'}, {Company: 'Nothing', Manufacturing: 'India'} ]; array.sort(func); document.getElementById("para").innerHTML = "After sorting "Manufacturing" in descending order: " + JSON.stringify(array); }; </script> </body> </html>

As the output says, we have specified the compare() function that the sort should be done based on the "Manufacturing" in descending order.

Javascript sort array of objects by property

Updated on 22-Sep-2022 12:24:14

  • Related Questions & Answers
  • Sort array of objects by string property value - JavaScript
  • Sort Array of objects by two properties in JavaScript
  • Sorting an array objects by property having null value in JavaScript
  • Sort an array of objects by multiple properties in JavaScript
  • Sorting an array of objects by property values - JavaScript
  • How to Sort object of objects by its key value JavaScript
  • Filter array of objects by a specific property in JavaScript?
  • Retrieve property value selectively from array of objects in JavaScript
  • Sort array according to the date property of the objects JavaScript
  • Group objects by property in JavaScript
  • Java Program to Sort ArrayList of Custom Objects by Property
  • Searching objects by value in JavaScript
  • Sort MongoDB Collection by Array value?
  • JavaScript: Sort Object of Objects
  • Sorting an array of objects by an array JavaScript

How do you sort an array of objects based on a property in JavaScript?

To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

How do you sort an array of objects by property value?

Example 1: Sort Array by Property Name In the above program, the sort() method is used to sort an array by the name property of its object elements. The sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case).

How do you filter an array of objects in JavaScript based on property value?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

How do you sort an array of objects by two fields in JavaScript?

sort(function (a, b) { var aSize = a. gsize; var bSize = b. gsize; var aLow = a..
filter unique values from each col/key of sort..
put in order or reverse it..
add weights width zeropad for each object based on indexOf(value) keys values..
sort using caclutated weights..