Search code examples
javascriptreactjsnative

How to sort a complex array like this?


I am a beginner. How to sort this array according to the orderId value?

const fruitFrom = {
  apple: [
      { 'country': 'U.S', 'orderId': 2 }, 
      { 'country': 'France', 'orderId': 2 }
    ],
  pineapple: [
      { 'country': 'U.S', 'orderId': 1 },
      { 'country': 'Italy', 'orderId': 1 }
    ]
};

I hope to sort above like the following. Under each fruite, the orderID will be same.

fruitFrom = {
  pineapple: [
          { 'country': 'U.S', 'orderId': 1 },
          { 'country': 'Italy', 'orderId': 1 }
        ],
  apple: [
          { 'country': 'U.S', 'orderId': 2 }, 
          { 'country': 'France', 'orderId': 2 }
        ]
};    

I try this, but 'can't read undefined properties (reading 'orderId')

let sortedArray = fruitFrom.sort((a, b) => a[0].orderId - b[0].orderId)

Solution

  • Assuming that your original array should actually be an object, you could do the following:

    const fruitFrom = {
      apple: [
          { 'country': 'U.S', 'orderId': 2 }, 
          { 'country': 'France', 'orderId': 2 }
        ],
      pineapple: [
          { 'country': 'U.S', 'orderId': 1 },
          { 'country': 'Italy', 'orderId': 1 }
        ]
    };
    const res=Object.fromEntries(Object.entries(fruitFrom).sort(([_,[a]],[__,[b]])=>a.orderId-b.orderId));
    console.log(res);

    However, there have been many discussions over the order of properties in JavaScript objects, see here: Does JavaScript guarantee object property order?.