YogeshChauhan . com

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;

// Output

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

Credit: w3schools


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

How to add a scroll back to top button using JavaScript and CSS?CSSHow to add a Bar Chart in Angular App?AngularThe Complete Basic Explanation of PHP SessionsPHPUnderstanding the confusing and handy “This” keyword in JavaScriptJavaScriptHow to Secure Web or Mobile Browsers?MiscHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSSHow to select an element using its ID without the high specificity of the ID selector?CSSThe simple difference between var, let and const in JavascriptJavaScriptLearn to Implement Estimated Reading Time using PHP Part 2: Final Implementation with Source CodePHPHow to create rotating texts using JavaScript and CSS?CSSHow to overwrite file contents with new content in PHP?PHPHow to add Go Back button in Swift 5?Swift