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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
SQL ALL OperatorSQL/MySQLWhat’s a Strict mode in JavaScript?JavaScriptHow to test the WordPress 5.9 Beta 4?WordPressAmpersand (Parent Selector) in SCSS (Sass)SCSSHow to add Local State to a Class in React?ReactWordPress plugin development: How to fix a SQL injection?WordPressAdd animated hamburgers menu using Hamburgers collection on GitHubCSSHow to create a Horizontal Scroll on button click using JavaScript?JavaScriptForcing the domain to serve securely using HTTPSMiscellaneousWhat is Prototypal Inheritance in JavaScript?JavaScriptfor @each loop in SCSSSCSSHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScript