var originalArray = [
{
name: 'Shop1',
stock: [
{ name: 'Apples', quantity: [{ id: "something", time: 11 }, { id: "something", time: 44 }, { id: "something", time: 53 }] },
{ name: 'Bananas', quantity: [{ id: "something", time: 3 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
{ name: 'Grapes', quantity: [{ id: "something", time: 2 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
{ name: 'Pineapple', quantity: [{ id: "something", time: 8 }, { id: "something", time: 91 }, { id: "something", time: 3 }] }
]
},
{
name: 'Shop2',
stock: [
{ name: 'Laptop', quantity: [{ id: "something", time: 31 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
{ name: 'Phone', quantity: [{ id: "something", time: 1 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
{ name: 'Tablet', quantity: [{ id: "something", time: 111 }, { id: "something", time: 11 }, { id: "something", time: 323 }] }
]
}
];
For instance, in the provided array, stock
and quantity
are nested keys with an array of objects as their value.
Shop2
has
{ id: "something", time: 323 }
which has a higher time than any item in Shop1
After sorting,
Shop2
will be first in the list and Shop1
will be in second position, and so on, time descending
My code is not correctly sorting the shops.
It should not sort the nested array in stock & quantity, just sort the Shop order by time descending
const sorted = originalArray
.map(shop => shop.stock
.map(stk => stk.quantity
.map(item => Object.entries(item)[1])))
.sort((a, b) => b[1].time - a[1].time)
.map(item => item[1])
console.log(JSON.stringify(sorted));
EXPECTED OUTPUT
// sorted array
[
{
name: 'Shop2',
stock: [
{ name: 'Laptop', quantity: [{ id: "something", time: 31 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
{ name: 'Phone', quantity: [{ id: "something", time: 1 }, { id: "something", time: 11 }, { id: "something", time: 23 }] },
{ name: 'Tablet', quantity: [{ id: "something", time: 111 }, { id: "something", time: 11 }, { id: "something", time: 323 }] }
]
},
{
name: 'Shop1',
stock: [
{ name: 'Apples', quantity: [{ id: "something", time: 11 }, { id: "something", time: 44 }, { id: "something", time: 53 }] },
{ name: 'Bananas', quantity: [{ id: "something", time: 3 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
{ name: 'Grapes', quantity: [{ id: "something", time: 2 }, { id: "something", time: 91 }, { id: "something", time: 3 }] },
{ name: 'Pineapple', quantity: [{ id: "something", time: 8 }, { id: "something", time: 91 }, { id: "something", time: 3 }] }
]
}
]