Sort Array of Objects: JavaScript Hacks for Efficient Coding

November 14, 2023
Sort Array of Objects: JavaScript Hacks for Efficient Coding
Table of Contents
  • sort()
  • Without sort()
  • Browser Compatibility

In JavaScript, arrays are used to store multiple values in a single variable. But what if you want to store multiple variables in each array element? This is where objects come into play.

1var array = [
2 { name: "John", age: 30, city: "New York" },
3 { name: "Jane", age: 20, city: "San Francisco" },
4 { name: "Mary", age: 25, city: "Boston" },
5];

You might find yourself asking, "Can you sort an array of objects in JavaScript?" The answer is yes, and we'll show you how.

sort()

The sort() method sorts the items of an array. When sorting an array of objects, you specify the property to sort by.

1array.sort(function (a, b) {
2 return a.age - b.age;
3});

This will sort the array of objects by age in ascending order.

Without sort()

But what if you're wondering "How to sort array of objects in JavaScript without sort function?" You can use a simple for loop.

1for (let i = 0; i < array.length; i++) {
2 for (let j = i + 1; j < array.length; j++) {
3 if (array[i].age > array[j].age) {
4 let temp = array[i];
5 array[i] = array[j];
6 array[j] = temp;
7 }
8 }
9}

This will also sort the array of objects by age in ascending order.

Browser Compatibility

All modern browsers support the methods used in this tutorial. For more advanced JavaScript tutorials, check out our JavaScript course. If you're new to web development, start with our introduction to web development course.

For further reading, I recommend Mozilla Developer Network's JavaScript Guide and W3Schools' JavaScript Tutorial.

Related courses

1 Course

Javascript Fundamentals Course

Javascript Fundamentals

4.7+
834 reviews

Stay Ahead with Code highlights

Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.

3D Letter

Related articles

114 Articles

Start learning for free

If you've made it this far, you must be at least a little curious. Sign up and grow your programming skills with Code Highlights.

Start learning for free like this happy man with Code Highlights