I have an array i'm attempting to sort by the amount of total orders. I am having an issue finding a way to solve this goal. I've tried looking up examples and couldn't find a question similar to what I am attempting to do
I currently have an array of data that I am trying to sort by the largest amount of orders to the least amount of orders.
I am currently sorting by the length of the array which is not giving what I want because some orders can have a count of 10. Which would be greater then some arrays of a higher length but lower count.
How can I sort by the total of items.amount within the sort method?
const orders = [{
id: 242,
items: [{
id: '3000',
amount: 2
},
{
id: '3001',
amount: 1
},
{
id: '3002',
amount: 4
}
]
}, {
id: 1,
items: [{
id: '3000',
amount: 10
}]
},
{
id: 14,
items: [{
id: '3211',
amount: 3
},
{
id: '3000',
amount: 1
}
]
}
]
const sortedOrders = orders.sort(
(taskA, taskB) =>
taskB.items.length - taskA.items.length
);
console.log(sortedOrders)
I am expecting an output like this with amount: 10 being the greatest value so displaying first:
[
{
"id": 242,
"items": [
{
"id": 1,
"items": [
{
"id": "3000",
"amount": 10
}
]
},
{
"id": "3000",
"amount": 2
},
{
"id": "3001",
"amount": 1
},
{
"id": "3002",
"amount": 4
}
]
},
{
"id": 14,
"items": [
{
"id": "3211",
"amount": 3
},
{
"id": "3000",
"amount": 1
}
]
}
]
amountbut your code sorts onitems.length. One of those two is not what you want.