JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to sort the keys of an object in JavaScript?

To sort the keys of an object, you have to get all keys as array elements. To do this, call the Object.keys() method. Once you have all the keys, then call the sort() method on the array to get the sorted keys. Finally, call the reduce() method to iterate through the sorted array and assign each key and its value to the accumulator.

In this way, you can sort the keys of an object.

In the entire process, the original object is not modified; rather a new object is created with sorted key-value pairs.

let pdt = {
  name: 'Green Floral Midi Dress',
  id: 823,
  price: '$45',
  fabric: 'Polyester'
}

let sorted = Object.keys(pdt).reduce((accumulator, current)=>{
  accumulator[current] = pdt[current];
  return accumulator;
}, {});
console.log(sorted);

Output

{
  fabric: "Polyester",
  id: 823,
  name: "Green Floral Midi Dress",
  price: "$45"
}

Note: Object class does not provide the sort() method to sort the keys of an object; that is why you have to follow the steps explained in this tutorial to get the sorted keys of an object.

Here is the explanation of the code:

1. The Object.keys() method returns an array whose elements are keys of an object.

let pdt = {
  name: 'Green Floral Midi Dress',
  id: 823,
  price: '$45',
  fabric: 'Polyester'
}

let keys = Object.keys(pdt);
console.log(keys); //["name", "id", "price", "fabric"]

2. The sort() method sorts the array alphabetically.

let keys = ["name", "id", "price", "fabric"];
keys.sort();
console.log(keys); //["fabric", "id", "name", "price"]

3. The array reduce() method is one of the array iteration methods used to loop through the array. It takes a callback function that is called on each element of the array. The callback function accepts two parameters, accumulator and current value.

You assign a key-value pair to the accumulator and return it on each iteration. After the last iteration, the reduce() method returns the accumulator, the sorted key-value pairs of the object.

It is important to note that you must pass an empty object as an initial value to the reduce() method.

Iteration accumulator currentValue returned value
1st Iteration {} "fabric" {fabric: "Polyester"}
2nd Iteration {fabric: "Polyester"} "id" {fabric: "Polyester", id: 823}
3rd Iteration {fabric: "Polyester", id: 823} "name" {fabric: "Polyester", id: 823, name: "Green Floral Midi Dress"}
4th Iteration {fabric: "Polyester", id: 823, name: "Green Floral Midi Dress"} "price" {fabric: "Polyester", id: 823, name: "Green Floral Midi Dress", price: "$45"}

Recommended Posts