JavaScript: Sort Object of Objects

Suppose we have an Object of Objects like this:

const obj = {
  "CAB": {
    name: 'CBSSP',
    position: 2
  },
  "NSG": {
    name: 'NNSSP',
    position: 3
  },
  "EQU": {
    name: 'SSP',
    position: 1
  }
};

We need to write a JavaScript function that sorts the sub-objects based on the 'position' property in ascending order.

Method 1: Using Object.keys() and Array Indexing

This approach creates an ordered array and places keys at positions corresponding to their 'position' values:

const obj = {
  "CAB": {
    name: 'CBSSP',
    position: 2
  },
  "NSG": {
    name: 'NNSSP',
    position: 3
  },
  "EQU": {
    name: 'SSP',
    position: 1
  }
};

const sortByPosition = obj => {
  const order = [], res = {};
  Object.keys(obj).forEach(key => {
    return order[obj[key]['position'] - 1] = key;
  });
  order.forEach(key => {
    res[key] = obj[key];
  });
  return res;
}

console.log(sortByPosition(obj));
{
  EQU: { name: 'SSP', position: 1 },
  CAB: { name: 'CBSSP', position: 2 },
  NSG: { name: 'NNSSP', position: 3 }
}

Method 2: Using Object.entries() and sort()

A more flexible approach that converts to entries, sorts, and reconstructs the object:

const sortObjectByPosition = (obj) => {
  return Object.fromEntries(
    Object.entries(obj).sort(([, a], [, b]) => a.position - b.position)
  );
};

const obj = {
  "CAB": { name: 'CBSSP', position: 2 },
  "NSG": { name: 'NNSSP', position: 3 },
  "EQU": { name: 'SSP', position: 1 }
};

console.log(sortObjectByPosition(obj));
{
  EQU: { name: 'SSP', position: 1 },
  CAB: { name: 'CBSSP', position: 2 },
  NSG: { name: 'NNSSP', position: 3 }
}

Sorting in Descending Order

To sort in descending order, simply reverse the comparison in Method 2:

const sortObjectDescending = (obj) => {
  return Object.fromEntries(
    Object.entries(obj).sort(([, a], [, b]) => b.position - a.position)
  );
};

const obj = {
  "CAB": { name: 'CBSSP', position: 2 },
  "NSG": { name: 'NNSSP', position: 3 },
  "EQU": { name: 'SSP', position: 1 }
};

console.log(sortObjectDescending(obj));
{
  NSG: { name: 'NNSSP', position: 3 },
  CAB: { name: 'CBSSP', position: 2 },
  EQU: { name: 'SSP', position: 1 }
}

Comparison

Method Flexibility Readability Use Case
Array Indexing Limited Moderate Sequential positions starting from 1
Object.entries() + sort() High High Any numeric positions, ascending/descending

Conclusion

Use Object.entries() with sort() for flexibility and readability. The array indexing method works well for sequential positions but is less adaptable to different sorting requirements.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements