Yogesh Chauhan's Blog

Sorting Object Arrays in JavaScript

in JavaScript on August 12, 2020

We can write a compare function to compare the property values of an object.

For example:


var cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

cars.sort(function(a, b){return a.year - b.year});

Even if objects have properties of different data types, the sort() method can be used to sort the array.

But that was for comparing the number properties. 

Comparing string properties is a little more complex:


var cars = [
  { type: "Volvo", year: 2016 },
  { type: "Saab", year: 2001 },
  { type: "BMW", year: 2010 },
];

cars.sort(function (a, b) {
  var x = a.type.toLowerCase();
  var y = b.type.toLowerCase();
  if (x < y) {
    return -1;
  }
  if (x > y) {
    return 1;
  }
  return 0;
});
console.log(cars);

// Output

[
  { type: 'BMW', year: 2010 },
  { type: 'Saab', year: 2001 },
  { type: 'Volvo', year: 2016 }
]

Credit: w3schools


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Use inline if to make a shorter conditional syntax in ReactReactKilling A Project Part 1: What criteria should be used to cancel/kill a project?MiscellaneousCREATE TABLE Examples in PostgreSQLPostgresPre-defined DatePipe format options in Angular 9AngularUnderstand Inheritance in PHP in this Basic Example (For Beginners)PHPHow to Make CSS Lists Bullets Smaller?CSSGlobal JavaScript methods to convert variables to numbersJavaScriptHow to create Flickering Texts using CSS?CSSWill SQL (Relational) Database become obsolete?SQL/MySQLThe order Property in Flex Items in CSSCSSSequence generator (range) using JavaScript Array.from()JavaScriptHow to force your website to load securely with an .htaccess file?Miscellaneous