Beginner Coder
Beginner Coder

Reputation: 226

How to sort this array according to month and date?

I want to sort this array according to its month

["Month", "Apple", "Banana", "Mango"]
1: (4) ["Apr-08", 30, 0, 0]
2: (4) ["Apr-16", 26, 0, 21]
3: (4) ["Jul-08", 16.25, 9.25, 0]
4: (4) ["Feb-07", 58, 0, 0]
5: (4) ["Feb-08", 11, 0, 0]
6: (4) ["Jun-07", 4, 0, 0]
7: (4) ["Jul-07", 2.25, 0, 0]

I am expecting this result after sorting according to its month and date ?

["Month", "Apple", "Banana", "Mango"]
1: (4) ["Feb-07", 58, 0, 0]
2: (4) ["Feb-08", 11, 0, 0]
3: (4) ["Apr-08", 30, 0, 0]
4: (4) ["Apr-16", 26, 0, 21]
5: (4) ["Jun-07", 4, 0, 0]
6: (4) ["Jul-08", 16.25, 9.25, 0]
7: (4) ["Jul-07", 2.25, 0, 0]

I think i should create variable which belong all months like this and compare

var allMonths = ['Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

Upvotes: 0

Views: 55

Answers (3)

wangdev87
wangdev87

Reputation: 8751

You can use sort method

const ary = [
  ["Apr-08", 30, 0, 0],
  ["Apr-16", 26, 0, 21],
  ["Jul-08", 16.25, 9.25, 0],
  ["Feb-07", 58, 0, 0],
  ["Feb-08", 11, 0, 0],
  ["Jun-07", 4, 0, 0],
  ["Jul-07", 2.25, 0, 0]
]

const output = ary.sort((a, b) => new Date(a[0]) > new Date(b[0]) ? 1 : -1)

console.log(output)

Upvotes: 0

lamboktulus1379
lamboktulus1379

Reputation: 370

let arr = [
 ["Apr-08", 30, 0, 0],                  
 ["Apr-16", 26, 0, 21],
 ["Jul-08", 16.25, 9.25, 0],
 ["Feb-07", 58, 0, 0],
 ["Feb-08", 11, 0, 0],
 ["Jun-07", 4, 0, 0],
 ["Jul-07", 2.25, 0, 0]];

 var allMonths = ['Jan','Feb','Mar', 'Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

arr.sort((a, b) => {
    return allMonths.findIndex((e) => e === a[0].substr(0, 3)) -  allMonths.findIndex((e) => e === b[0].substr(0, 3))
 }    
 );

Upvotes: 0

syarul
syarul

Reputation: 2187

const ary = [
  ["Apr-08", 30, 0, 0],
  ["Apr-16", 26, 0, 21],
  ["Jul-08", 16.25, 9.25, 0],
  ["Feb-07", 58, 0, 0],
  ["Feb-08", 11, 0, 0],
  ["Jun-07", 4, 0, 0],
  ["Jul-07", 2.25, 0, 0]
]

const output = ary.sort((a, b) =>
  new Date(a[0]) > new Date(b[0]) ? 1 : -1
)

console.log(output)

Upvotes: 1

Related Questions