how to sort array of objects in javascript with code examples

Sorting an array of objects in JavaScript is a common task that can be achieved in different ways. The most straightforward approach is to use the built-in sort() method of arrays, but it may require additional logic to handle sorting by multiple properties or in a specific order.

In this article, we will explore different methods to sort an array of objects in JavaScript and discuss their advantages and disadvantages. We will also provide code examples to help you understand the concepts better.

Using the Array.sort() Method

The simplest way to sort an array of objects is to use the sort() method. By default, sort() sorts the elements in ascending order. The method uses the less-than operator < to compare the values of two elements, and returns a negative, zero, or positive value based on the comparison. The negative value means the first element is smaller than the second, zero means they are equal, and positive means the first element is greater than the second.

Here's an example of using the sort() method to sort an array of objects by a property named "name":

const people = [
  { name: "John", age: 28 },
  { name: "Jane", age: 31 },
  { name: "Jim", age: 33 },
];

people.sort((a, b) => (a.name > b.name ? 1 : -1));

console.log(people);
// Output:
// [
//   { name: "Jane", age: 31 },
//   { name: "Jim", age: 33 },
//   { name: "John", age: 28 },
// ]

In this example, the sort() method takes a callback function as an argument, which compares the name property of two objects. The callback function returns 1 if the first object's name is greater than the second, and -1 otherwise. This makes the sort() method sort the elements in ascending order based on the name property.

Sorting by Multiple Properties

Sometimes, you may need to sort an array of objects by multiple properties. For example, you may want to sort the array by name in ascending order, and by age in descending order. In this case, you can write a custom sorting function that takes into account multiple properties.

Here's an example of sorting an array of objects by multiple properties:

const people = [
  { name: "John", age: 28 },
  { name: "Jane", age: 31 },
  { name: "Jim", age: 33 },
  { name: "Jim", age: 25 },
];

people.sort((a, b) => {
  if (a.name === b.name) {
    return b.age - a.age;
  }
  return a.name > b.name ? 1 : -1;
});

console.log(people);
// Output:
// [
//   { name: "Jane", age: 31 },
//   { name: "Jim", age: 33 },
//   { name: "Jim", age: 25 },
//   { name: "John", age: 28 },
// ]

In this example, the sorting function first checks if the names of two objects are equal. If they are, it returns the difference of their ages to sort by age in descending order. If the names are not

Sorting in Descending Order

To sort an array of objects in descending order, you can simply reverse the order of comparison in the sorting function. For example, the following code sorts an array of objects by the age property in descending order:

const people = [
  { name: "John", age: 28 },
  { name: "Jane", age: 31 },
  { name: "Jim", age: 33 },
];

people.sort((a, b) => b.age - a.age);

console.log(people);
// Output:
// [
//   { name: "Jim", age: 33 },
//   { name: "Jane", age: 31 },
//   { name: "John", age: 28 },
// ]

Sorting Based on a Dynamic Property

In some cases, you may need to sort an array of objects based on a property that can change dynamically. For example, you may have a dropdown that allows the user to select the property to sort by. To handle this scenario, you can pass the property name as an argument to the sorting function.

Here's an example of sorting an array of objects based on a dynamic property:

const people = [
  { name: "John", age: 28 },
  { name: "Jane", age: 31 },
  { name: "Jim", age: 33 },
];

const sortBy = "age";

people.sort((a, b) => (a[sortBy] > b[sortBy] ? 1 : -1));

console.log(people);
// Output:
// [
//   { name: "John", age: 28 },
//   { name: "Jane", age: 31 },
//   { name: "Jim", age: 33 },
// ]

In this example, the sortBy variable holds the property name to sort by. The sorting function uses bracket notation to access the property value, making the sorting function reusable for different properties.

Sorting a Complex Object

In some cases, you may have an array of complex objects, such as an array of nested objects or an array of objects with different properties. In this case, you may need to write a custom sorting function to handle the complexity.

Here's an example of sorting an array of nested objects:

const people = [
  {
    name: "John",
    address: {
      city: "New York",
      zip: 10001,
    },
  },
  {
    name: "Jane",
    address: {
      city: "Los Angeles",
      zip: 90001,
    },
  },
  {
    name: "Jim",
    address: {
      city: "Chicago",
      zip: 60601,
    },
  },
];

const sortBy = "address.zip";

people.sort((a, b) => {
  const sortByProperties = sortBy.split(".");
  let aValue = a;
  let bValue = b;
  for (const property of sortByProperties) {
    aValue = aValue[property];
    bValue = bValue[property];
  }
  return aValue > bValue ? 1 : -1;
});

console.log(people);
// Output:
## Popular questions 
1. What is the default sorting order in JavaScript? 

Answer: By default, JavaScript sorts arrays of primitive values in alphabetical order, and arrays of objects in the order in which they were added to the array.

2. How can you sort an array of objects in JavaScript? 

Answer: You can sort an array of objects in JavaScript using the `sort()` method, along with a custom comparison function that specifies the sorting order. The comparison function should return a value less than 0 if `a` should be sorted before `b`, a value greater than 0 if `b` should be sorted before `a`, and 0 if they are equal.

3. How can you sort an array of objects by a specific property? 

Answer: To sort an array of objects by a specific property, you can use the comparison function in the `sort()` method to compare the values of the desired property for each object. For example, to sort an array of objects by the `age` property, you can write the following code:

const people = [
{ name: "John", age: 28 },
{ name: "Jane", age: 31 },
{ name: "Jim", age: 33 },
];

people.sort((a, b) => a.age – b.age);

4. Can you sort an array of objects in descending order in JavaScript? 

Answer: Yes, you can sort an array of objects in descending order in JavaScript by reversing the order of comparison in the sorting function. For example, the following code sorts an array of objects by the `age` property in descending order:

const people = [
{ name: "John", age: 28 },
{ name: "Jane", age: 31 },
{ name: "Jim", age: 33 },
];

people.sort((a, b) => b.age – a.age);

5. How can you sort an array of objects based on a dynamic property in JavaScript? 

Answer: To sort an array of objects based on a dynamic property in JavaScript, you can pass the property name as an argument to the sorting function, and use bracket notation to access the property value in the comparison function. For example, the following code sorts an array of objects based on a dynamic property:

const people = [
{ name: "John", age: 28 },
{ name: "Jane", age: 31 },
{ name: "Jim", age: 33 },
];

const sortBy = "age";

people.sort((a, b) => (a[sortBy] > b[sortBy] ? 1 : -1));

### Tag 
Arraysorting
Posts created 2498

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top