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
How to create a pricing table using flex in CSS?CSSHow to hide and show menu on scroll using JavaScript and CSS?CSSList of all Pseudo Elements in CSSCSSWhat’s a Closure in JavaScript?JavaScriptWhat is XP (Extreme Programming) and When should it be used?MiscellaneousHow to insert Bootstrap 4 in Angular 9 app?AngularHow to create rotating texts using JavaScript and CSS?CSSQuick Introduction to 11 Array Iteration Methods in JavaScriptJavaScriptSteps to Install Microsoft SQL Server on a MacOSSQL/MySQLWhat is Prototypal Inheritance in JavaScript?JavaScriptJavaScript Input Validation Theme Park Example using throw StatementJavaScriptHow to use $INSERT command in Envision Basic?Envision Basic