yobee310
yobee310

Reputation: 13

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)

Upvotes: 1

Views: 80

Answers (2)

sandip rana
sandip rana

Reputation: 66

Do you mean your array is like this,

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

If yes, then you should do something like this,

const data = fruitFrom.sort((a, b) => (Object.values(a)[0][0].orderId) - (Object.values(b)[0][0].orderId));

console.log(data);

I hope this will work for you.

Upvotes: 4

Carsten Massmann
Carsten Massmann

Reputation: 28196

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?.

Upvotes: 0

Related Questions