Javascript排序对象数组

时间:2017-07-12 14:56:55

标签: typescript

我有以下代码:

  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);
    });
  }

如您所见,它返回一个数组。我想按date(升序)对数组进行排序。

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

任何建议欢迎。

1 个答案:

答案 0 :(得分:1)

了解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));