Sorting JavaScript Object Properties by Value

Introduction

When working with JavaScript objects, there may be times when you need to sort an object’s properties based on their values. Although JavaScript objects do not maintain a specific order for their properties (as they are essentially unordered collections), it is possible to create a new sorted representation of the data. This tutorial will guide you through various methods to sort JavaScript object properties by their values, making use of modern JavaScript features where applicable.

Understanding the Problem

Consider an object like:

const list = {
  "you": 100,
  "me": 75,
  "foo": 116,
  "bar": 15
};

We want to sort this object by its values so that it becomes:

const sortedList = {
  "bar": 15,
  "me": 75,
  "you": 100,
  "foo": 116
};

Here, the goal is not merely sorting an array but transforming and reordering the properties of an object based on their associated values.

Method 1: Using Arrays for Sorting

One approach involves converting the object into an array, performing the sort operation, and then constructing a new object. This method leverages JavaScript’s array manipulation capabilities.

Steps:

  1. Convert Object to Array: Use Object.entries() to transform the object into an array of key-value pairs.
  2. Sort the Array: Utilize the Array.prototype.sort() function to order the array based on values.
  3. Rebuild the Object: Convert the sorted array back into an object using Object.fromEntries(), available from ES10.

Example Code:

const maxSpeed = {
  car: 300,
  bike: 60,
  motorbike: 200,
  airplane: 1000,
  helicopter: 400,
  rocket: 8 * 60 * 60
};

// Convert object to array, sort it by value, then convert back to an object
const sortedMaxSpeed = Object.fromEntries(
  Object.entries(maxSpeed).sort(([, a], [, b]) => a - b)
);

console.log(sortedMaxSpeed);

Method 2: Sorting Keys and Reconstructing the Object

An alternative method involves sorting the keys based on their values, then using these sorted keys to construct a new object.

Steps:

  1. Extract Keys: Use Object.keys() to obtain an array of object keys.
  2. Sort Keys: Sort this array by comparing the corresponding values in the original object.
  3. Reconstruct Object: Create a new object using the sorted keys and their associated values from the original object.

Example Code:

const list = {
  "you": 100,
  "me": 75,
  "foo": 116,
  "bar": 15
};

// Sort keys by corresponding value in the original object
const sortedKeys = Object.keys(list).sort((a, b) => list[a] - list[b]);

// Reconstruct a new object with sorted keys
const sortedList = {};
sortedKeys.forEach(key => {
  sortedList[key] = list[key];
});

console.log(sortedList);

Method 3: Sorting an Array of Objects

If your data is structured as an array of objects, sorting becomes straightforward using the Array.prototype.sort() function.

Example Code:

const arrayOfObjects = [
    { name: 'Diana', born: 1373925600000 },
    { name: 'Beyonce', born: 1366832953000 },
    { name: 'Albert', born: 1370288700000 },
    { name: 'Doris', born: 1354412087000 }
];

// Sort by date of birth
const sortedByDate = arrayOfObjects.slice().sort((a, b) => a.born - b.born);
console.log('Sorted by date:', sortedByDate);

// Sort by name
const sortedByName = arrayOfObjects.slice().sort((a, b) =>
    a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1
);
console.log('Sorted by name:', sortedByName);

Conclusion

Sorting object properties by their values in JavaScript can be achieved through various methods. Whether you choose to convert objects into arrays for sorting or directly manipulate keys and reconstruct objects, modern JavaScript offers powerful functions that simplify these tasks. Understanding these techniques allows developers to handle data more flexibly and efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *