Reputation: 7628
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?
Upvotes: 3
Views: 9969
Reputation: 1
Ensure your date format, dot is not an iso delimiter.
let toArr = (aDate) => aDate.split('.')
let toDate = ([year, month, day]) => new Date(year, month - 1, day)
let compareTrades = (a, b) => toDate(toArr(a.date)) - toDate(toArr(b.date))
let arr = [{
name: 'Apple',
trades: [{
date: '2017.01.01',
volume: 100
}, {
date: '1995.02.01',
volume: 150
}, {
date: '2008.01.01',
volume: 250
}]
}]
arr[0].trades.sort(compareTrades)
console.log(arr[0])
Upvotes: 0
Reputation: 2110
First in your array, date needs to be a string. You can than use arrays.sort with a function which returns the result
let arr = [
{
name : 'Apple',
trades : [
{date : "2017.01.01",
volume : 100
},
{date : "1995.02.01",
volume : 150
},
{date : "2008.01.01",
volume : 250
}
]
}
]
function compare(a,b) {
var dateA = new Date(a.date);
var dateB = new Date(b.date);
if (dateA > dateB)
return -1;
if (dateA < dateB)
return 1;
return 0;
}
arr[0].trades.sort(compare);
console.log(arr);
Upvotes: 1
Reputation: 10624
Read about array.sort()
and datetime
in Javascript.
let arr = [{
name: 'Apple',
trades: [{
date: '2017.01.01',
volume: 100
}, {
date: '1995.02.01',
volume: 150
}, {
date: '2008.01.01',
volume: 250
}]
}]
console.log(arr[0].trades.sort((tradeA, tradeB)=>{
return (new Date(tradeA.date) - new Date(tradeB.date)) * (-1)
// or return (new Date(tradeB.date) - new Date(tradeA.date))
}))
Upvotes: 2
Reputation: 1480
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.
Upvotes: 7