Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort nested array of object 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
  }]
}]

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?

like image 807
ton1 Avatar asked May 23 '26 21:05

ton1


1 Answers

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.

like image 107
Nikhilesh K V Avatar answered May 26 '26 10:05

Nikhilesh K V