How to Convert a JavaScript Object to an Array and Sort it?

Sometimes, we want to convert a JavaScript object to an array and sort it.

In this article, we’ll look at how to convert a JavaScript object to an array and sort it.

Convert a JavaScript Object to an Array and Sort it

To convert a JavaScript object to an array and sort it, we can use the Object.entries method to return an array of key value pairs, then use JavaScript array’s map method to return an array with the object values.

Then we can use the JavaScript array sort method to sort the returned entries.

For instance, we write:

const data = {
  1: {
    displayName: "Dude1",
    email: "[email protected]<mailto:[email protected]>",
    lastActive: 1296980700,
    level: 57,
    timeout: 12969932837
  },
  2: {
    displayName: "Dude2",
    email: "[email protected]<mailto:[email protected]>",
    lastActive: 1296983456,
    level: 28,
    timeout: 12969937382
  },
  3: {
    displayName: "Dude3",
    email: "[email protected]<mailto:[email protected]>",
    lastActive: 1296980749,
    level: 99,
    timeout: 129699323459
  }
}

const arr = Object
  .entries(data)
  .map(([key, obj]) => {
    return {
      ...obj,
      index: key
    }
  })
  .sort((x, y) => {
    return x.index - y.index
  });
console.log(arr)

to convert the data object into an array and the sort the entries.

We call Object.entries to return an array of key-value pairs in the data object.

Then we call map with a callback that merges obj with the index set to the key and apply this operation to each entry.

Next, we call sort with a callback that returns x.index - y.index to sort the entries.

As a result, arr is:

[
  {
    "displayName": "Dude1",
    "email": "[email protected]<mailto:[email protected]>",
    "lastActive": 1296980700,
    "level": 57,
    "timeout": 12969932837,
    "index": "1"
  },
  {
    "displayName": "Dude2",
    "email": "[email protected]<mailto:[email protected]>",
    "lastActive": 1296983456,
    "level": 28,
    "timeout": 12969937382,
    "index": "2"
  },
  {
    "displayName": "Dude3",
    "email": "[email protected]<mailto:[email protected]>",
    "lastActive": 1296980749,
    "level": 99,
    "timeout": 129699323459,
    "index": "3"
  }
]

Conclusion

To convert a JavaScript object to an array and sort it, we can use the Object.entries method to return an array of key value pairs, then use JavaScript array’s map method to return an array with the object values.

Then we can use the JavaScript array sort method to sort the returned entries.