let arr = [{
name: 'Apple',
trades: [{
date: '2017.01.01',
volume: 100
}, {
date: '1995.02.01',
volume: 150
}, {
date: '2008.01.01',
volume: 250
}]
}]
Hello, I googled many documents for sorting nested object in JavaScript, but I couldn't find the way of my case and I struggled so many hours so I want to ask to how can I sort above array of objects.
What I expected result is sort array of object by trades.date like this
sortedArray = [{
name: 'Apple',
trades: [{
date: '2017.01.01',
volume: 100
}, {
date: '2008.01.01',
volume: 250
}, {
date: '1995.02.01',
volume: 150
}]
}]
How can I do this?
arr[0].trades.sort(function(a, b) {
return (new Date(b.date) - new Date(a.date));
});
You can use the array's sort method for achieving this. If you want to sort in the reverse order then just swap a and b in the return code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With