Search code examples
javascriptarraysobjectfunctional-programmingjavascript-objects

How to sort object of arrays by nested property in JavaScript


I have the following object:

const obj = {
  A: [{
    capacity: 100
  }, {
    capacity: 100
  }, {
    capacity: 100
  }],
  B: [{
    capacity: 500
  }, {
    capacity: 500
  }, {
    capacity: 500
  }],
  C: [{
    capacity: 300
  }, {
    capacity: 300
  }, {
    capacity: 300
  }]
}

I need to transform to an object with the same shape but with the keys sorted by capacity. To note, the capacity of each object in the arrays (A, B, C) is always the same within the same object. So we can take the first occurrence for example

Expected result:

const obj = {
  A: [{
    capacity: 100
  }, {
    capacity: 100
  }, {
    capacity: 100
  }],
  C: [{
    capacity: 300
  }, {
    capacity: 300
  }, {
    capacity: 300
  }],
  B: [{
    capacity: 500
  }, {
    capacity: 500
  }, {
    capacity: 500
  }]
}

None of my approaches worked out. An example:

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

console.log(sortByPosition(obj));

Here's a fiddle


Solution

  • const obj = {
      A: [ { capacity: 100 }, { capacity: 100 }, { capacity: 100 } ],
      B: [ { capacity: 500 }, { capacity: 500 }, { capacity: 500 } ],
      C: [ { capacity: 300 }, { capacity: 300 }, { capacity: 300 } ]
    };
    
    console.log(Object.fromEntries(Object.entries(obj)
      .sort(([i,a],[j,b])=>a[0].capacity-b[0].capacity)));