1

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)
yobee310
  • 13
  • 3

2 Answers2

4

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.

RRR
  • 3,509
  • 4
  • 29
  • 38
0

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

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • If I change the format of data, it works! I must study about the format of array first. Thanks a lot. – yobee310 Jan 05 '23 at 06:38