Sorting Object Arrays in JavaScript
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;

// Output

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

Credit: w3schools


Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 5 How to create flickering text using CSS? Mar 4 How to use data-* Attributes in HTML? Mar 4 The substr() method in JavaScript and how it’s different from substring() Mar 4 A complete guide to add responsive YouTube videos using HTML and CSS Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress?

You might also like these

How to implement NSNumberFormatter in Swift for currency?SwiftHow to avoid element shift on border change while hovering in CSS?CSSHow to show confirmation alerts with OK and cancel buttons using Swift 5?SwiftIN and BETWEEN Operators in SQLSQL/MySQLHow to Use password_hash and password_verify to Secure Your User’s Data (Especially Passwords)?PHPHow to get start index and end index (as int) of substring in Swift?SwiftWhat is PostgreSQL? How similar or different it is from SQL?PostgresWhat is Host Hardening and What are some Important Hardening Steps?MiscHow to get previous days or next days in PHP?PHPWhat is the best way to add JavaScript Code into HTML?HTMLHow to add navigation menu in Angular 9 app?AngularHow to use HTML picture Tag?HTML