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


amazon

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 add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS? #Aug 1 What is Zdog? #Aug 1 How to add before after image effect using pure CSS? #Jul 31 Add animation to your skills bar using CSS #Jul 31 Use SwiperJS to create mobile touch sliders fast
You might also like these
2 Ways we can create an Array in JavaScriptJavaScriptComponents and Props in ReactReactCan Firewall and IDPS Stop DDoS Attack?MiscellaneousHow to set the permissions on all files and folders in Mac?MiscellaneousWordPress: How to get ACF field values from another post?WordPressPHP Login System using PDO Part 2: Login using Email or UsernamePHPCreate dynamic selectors using SCSS (Sass)SCSSGive buttons accessible namesUI/UXCheck whether a variable exists and not empty in PHPPHPFile System Integrity: How to Keep an Eye on Your Files and Folder Change?MiscellaneousWordPress: How to find all posts from a custom post type with multiple custom fields values?WordPressAdvanced nesting in Sass (SCSS) using at-rootSCSS