简体   繁体   中英

Sorting an Array of JSON objects by date - Angular2

I am trying to sort an array of objects in Angular2. The best way to explain is to give code examples:

 var activity = { SEQ_NO: -1, SIGNUP_NAME: "Testing Activity", SHORT_DESCRIPTION: "This activity min: 2, max: 25", EVENT_BEGIN_DATE: "2018/09/25", EVENT_END_DATE: "2018/09/25" }; 

The array is filled with objects like seen above. My goal is to take the array and sort it based on the date. I also call a convert date function that takes the numeric date and turns it to a readable format:

 convertDate(incomingDate) { var myDate = new Date(incomingDate); var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; console.log(days[myDate.getDay()]); var date = days[myDate.getDay()]+" "+(myDate.getMonth()+1)+'/'+myDate.getDate()+'/'+myDate.getFullYear(); //alert(date); return date; } 

So the activity object shown in this example will convert to: Tuesday 9/25/2018

How can I sort an array of these objects by date? When I display them, I am wanting to display them in order of months.

Thanks everyone in advanced.

First I would convert your date to a unix time as those will already be sorted by month.

Second I would simply just sort your array by that number .

Since you are using typescript.

component.html

 <div *ngFor="let sorted of sortedArray$ | async">
    {{sorted.start}} 
 </div>

component.ts

  list: any[] = [{
    start: '2018/09/25',
    content: 'second'
  },{
    start: '2018/08/10',
    content: 'first'
  }];

  sortedArray$: Observable<any[]>;

  constructor(public navCtrl: NavController) {
    this.sortedArray$ = Observable.of(this.list)
    .map((data) => {
        data.sort((a, b) => {
            return new Date(a.start.getTime()) > new Date(b.start.getTime());
        });
        return data;
    });
  }

When a string date is in the format yyyy/mm/dd it can be properly sorted without converting.

list.sort(function (a, b) {
  a = a.EVENT_BEGIN_DATE;
  b = b.EVENT_BEGIN_DATE;
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  }
  return 0;
});

You can then convert the dates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM