Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Parameters
4.
Return value
4.1.
Description
4.2.
The compare Function
4.3.
Creating, Displaying, & Sorting an Array
4.4.
JavaScript
4.5.
Sort an array of objects by Numbers
4.6.
JavaScript
4.7.
Sort an Array of Objects by Strings
4.8.
JavaScript
4.9.
Sort an Array of Objects by Dates
4.10.
JavaScript
5.
Frequently Asked Questions
5.1.
Can I sort in descending order?
5.2.
Does sorting alter the original array?
5.3.
Can I sort by multiple criteria?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Sort Array Of Objects Javascript

Author Ravi Khorwal
0 upvote

Introduction

Sorting through data is a task that virtually every developer encounters, & when it comes to JavaScript, sorting arrays of objects is a common challenge. Whether you're organizing user data, product information, or complex datasets, understanding how to effectively sort through this data is crucial. 

Sort Array Of Objects Javascript

This article will guide you through the ins and outs of sorting arrays of objects in JavaScript. You'll learn the syntax, how to utilize the compare function, & various methods to sort by numbers, strings, & even dates, equipping you with the skills to handle your data efficiently.

Syntax

The primary method used for sorting arrays in JavaScript is the Array.prototype.sort() function. This method sorts the elements of an array in place & returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

array.sort([compareFunction])
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parameters

The sort method can optionally take a compare function as a parameter, which specifies a function that defines the sort order. If omitted, the array elements are converted to strings & sorted according to each character's Unicode code point value.

function compare(a, b) {
  // Implementation for comparison
}

Return value

The sort method returns the sorted array. Remember, this method alters the original array & sorts the elements in place.

Description

When a compare function is provided, the array elements are sorted according to the return value of the compare function. If the function returns a value less than 0, it sorts a before b. If the function returns a value greater than 0, it sorts b before a. If the function returns 0, a & b are considered equal.

The compare Function

The compare function plays a crucial role in customizing the sort behavior. It takes two arguments, often referred to as a & b, which represent any two elements being compared in the array.

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

Creating, Displaying, & Sorting an Array

Let's start by creating & displaying an array of objects. We'll then apply the sorting techniques we've discussed.

  • JavaScript

JavaScript

let users = [

 { name: "Alice", age: 25 },

 { name: "Bob", age: 22 },

 { name: "Charlie", age: 28 }

];

console.log("Original array:", users);

Output

Output

Sort an array of objects by Numbers

Sorting by numbers, like ages or scores, is straightforward with the compare function. Here's how you can sort the users array by age:

  • JavaScript

JavaScript

let users = [

 { name: "Alice", age: 25 },

 { name: "Bob", age: 22 },

 { name: "Charlie", age: 28 }

];

console.log("Original array:", users);

users.sort(function(a, b) {

 return a.age - b.age;

});

console.log("Sorted by age:", users);

Output

Output

Sort an Array of Objects by Strings

Sorting by strings requires comparing the string properties. If you want to sort the users array by names, the compare function changes slightly:

  • JavaScript

JavaScript

let users = [

 { name: "Alice", age: 25 },

 { name: "Dia", age: 22 },

 { name: "Charlie", age: 28 }

];

console.log("Original array:", users);

users.sort(function(a, b) {

 let nameA = a.name.toUpperCase(); // ignore upper & lowercase

 let nameB = b.name.toUpperCase(); // ignore upper & lowercase

 if (nameA < nameB) {

   return -1;

 }

 if (nameA > nameB) {

   return 1;

 }

 return 0;

});

console.log("Sorted by name:", users);

Output

Output

Sort an Array of Objects by Dates

Sorting by dates involves comparing date objects. Assume each user object has a signupDate property. Here's how you'd sort by that date:

  • JavaScript

JavaScript

let users = [

 { name: "Alice", age: 25 },

 { name: "Dia", age: 22 },

 { name: "Charlie", age: 28 }

];


console.log("Original array:", users);

users.sort(function(a, b) {

 return new Date(a.signupDate) - new Date(b.signupDate);

});

console.log("Sorted by signup date:", users);

Output

Output

Frequently Asked Questions

Can I sort in descending order?

Yes, just reverse the comparison in your compare function.

Does sorting alter the original array?

Yes, the sort method sorts arrays in place & modifies the original array.

Can I sort by multiple criteria?

Absolutely, you can extend the compare function to include multiple conditions for a more refined sort.

Conclusion

Sorting arrays of objects in JavaScript is a fundamental skill that enhances your data manipulation capabilities. By mastering the use of the sort method & the compare function, you can efficiently organize your data by various criteria, making your applications more intuitive & user-friendly. With the examples & explanations provided, you're well-equipped to tackle sorting challenges in your projects.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Call apply bind in Javascript
Next article
Javascript Filter
Live masterclass