Sort array of objects by string property value in JavaScript

An array of objects basically means an array that contains one or more than one object. It is possible to sort an array by a user-defined function. The property of each object in the array is compared by this function.

For this purpose, we will use sort() method. This JavaScript built-in method sorts the elements of an array by ascending order and returns the shorted array.

Sort array of objects in ascending order

Here is the JavaScript program below to sort an array of objects by string value in ascending order.

let array = [
  { name: 'Samim', website: 'TutsJS', },
  { name: 'Ahmed', website: 'codespeedy', },
  { name: 'Faruque', website: 'SwiftSpeedy', },
];

function compare( a, b ) {
  if ( a.name < b.name ){
    return -1;
  }
  if ( a.name > b.name ){
    return 1;
  }
  return 0;
}

array.sort( compare );
console.log(array);

In the above program, I have created a comparison function to sort array objects by the value of  name key in ascending order.

Then passed the compare function into the sort method to compare two array elements.

Output:

[
{ name: 'Ahmed', website: 'CodeSpeedy' },
{ name: 'Faruque', website: 'SwiftSpeedy' },
{ name: 'Samim', website: 'TutsJS' }
]

As you can see in the above output, in the array of objects the value of name key has been sorted in ascending order.

Sort array in descending order

Here is the JavaScript program below to sort an array of objects by string value in descending order.

let array = [
  { name: 'Samim', website: 'TutsJS', },
  { name: 'Ahmed', website: 'codespeedy', },
  { name: 'Faruque', website: 'SwiftSpeedy', },
];

function compare( a, b ) {
  if ( a.name < b.name ){
    return 1;
  }
  if ( a.name > b.name ){
    return -1;
  }
  return 0;
}

array.sort( compare );
console.log(array);

A comparison function has been created in the above program to sort array objects by the value of the name key in descending order.

Output:

[
{ name: 'Samim', website: 'TutsJS' },
{ name: 'Faruque', website: 'SwiftSpeedy' },
{ name: 'Ahmed', website: 'codespeedy' }
]

As you can see in the above output, in the array of objects the value of name key has been sorted in descending order.

Leave a Reply

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