Home > Blockchain >  How to sort a complex array like this?
How to sort a complex array like this?

Time:01-05

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

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)

CodePudding user response:

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.

CodePudding user response:

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);

  • Related