-1

I have the following code:

  private restorePurchases(): Promise<any[]> {
    return new Promise<any[]>((resolve) => {
      let data: any[] =
        [
          {
            productId: 'com.thewhozoo.prod.message.30days',
            date: 1499869861370
          },
          {
            productId: 'com.thewhozoo.prod.message.3days',
            date: 1498869861369
          },
          {
            productId: 'com.thewhozoo.prod.message.10days',
            date: 1499869851369
          },
          {
            productId: 'com.thewhozoo.prod.message.3days',
            date: 1499869861369
          }
        ];

      resolve(data);
    });
  }

As you can see, it returns an array. I would like to sort the array by date (ascending).

this.restorePurchases().then((purchases: any[]) => {
    purchases.sort(by date);
});

Any advise welcome.

Endless
  • 34,080
  • 13
  • 108
  • 131
Richard
  • 8,193
  • 28
  • 107
  • 228
  • 1
    Possible duplicate of [Sorting an array of JavaScript objects](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Durga Jul 12 '17 at 15:01
  • Unless for some reason TypeScript prevents it, you should be using `return Promise.resolve(...)` instead of constructing a new promise and then invoking its `resolve` callback. – Alnitak Jul 12 '17 at 15:03

1 Answers1

1

See how Array.prototype.sort documentation.

this.restorePurchases().then((purchases: any[]) => {
     purchases.sort((a, b) => a.date - b.date);
});

const data = [
  {
    productId: 'com.thewhozoo.prod.message.30days',
    date: 1499869861370
  },
  {
    productId: 'com.thewhozoo.prod.message.3days',
    date: 1498869861369
  },
  {
    productId: 'com.thewhozoo.prod.message.10days',
    date: 1499869851369
  },
  {
    productId: 'com.thewhozoo.prod.message.3days',
    date: 1499869861369
  }
];

console.log(data.sort((a, b) => a.date - b.date));
Erazihel
  • 7,295
  • 6
  • 30
  • 53
  • Thank you, that works. I will mark this as the correct answer in 9 minutes when it allows me to. – Richard Jul 12 '17 at 15:01