Angular сортировка массива объектов по дате - PullRequest
0 голосов
/ 22 марта 2020

Я знаю, что существует множество похожих тем, но я пробовал их все, и ничего не работает.

Мой сценарий извлекает различные типы действий из разных БД и для каждого действия добавляет идентификатор и дату в общий массив (activiteList).

Файл TS:

_maj(id) {
    this.activiteList = [];

    this.csltList = [];
    this._getCslt(id);

    this.deplList = [];
    this._getDepl(id);

    console.log('Before sorting', this.activiteList);

    this.activiteList.sort(function (a, b) {
      return a.date - b.date;
    });

    console.log('After sorting', this.activiteList);
  }

_getCslt(id) {
  if (isDefined(id) && id !== '') {
    this.csltService.getCslt(id).toPromise().then(cslts => {
      this.csltList = [];
      if (isDefined(cslts)) {
        cslts.forEach((cslt) => {
          const csltTr = new CsltModel(
            new Date(cslt.csltDateTime),
            cslt.author,
            cslt.motif,
            cslt.userId,
            id
          );
          csltTr.id = cslt.id;
          this.csltList.push(csltTr);

          this.activiteList.push({
            'date': new Date(cslt.csltDateTime).getTime(),
            'type': 'cslt',
            'id': cslt.id
          });
        });
      }
      this.cd.markForCheck();
    });
  }
}

_getDepl(id) {
  if (isDefined(id) && id !== '') {
    this.deplService.getDepl(id).toPromise().then(depls => {
      this.deplList = [];
      if (isDefined(depls)) {
        depls.forEach((depl) => {
          const deplTr = new DeplModel(
            new Date(depl.deplDateTime),
            depl.author,
            depl.conclusion,
            depl.missions,
            depl.userId,
            id
          );
          deplTr.id = depl.id;
          this.deplList.push(deplTr);

          this.activiteList.push({
            'date': new Date(depl.deplDateTime).getTime(),
            'type': 'depl',
            'id': depl.id
          });
        });
      }
      this.cd.markForCheck();
    });
  }
}

В конце функции _maj я пытаюсь отсортировать массив activiteList по дате, который я сохранил как метки времени. Я перепробовал все найденные функции сортировки, предупреждение на консоли до и после сортировки остается прежним ...

[]
0: {date: 1584625856088, type: "cslt", id: "0aeae480-109d-4329-9be5-ef4f8933d550"}
1: {date: 1581506529640, type: "depl", id: "ebfc3f2a-54db-41ba-b9a2-982b6c2d4756"}
2: {date: 1584625891099, type: "depl", id: "696b15df-8f7d-42d5-af52-ec03b171c837"}
length: 3
__proto__: Array(0)

Заранее спасибо

1 Ответ

0 голосов
/ 22 марта 2020
myList = [{date: 1584625856088, type: "cslt", id: "0aeae480-109d-4329-9be5-ef4f8933d550"},{date: 1581506529640, type: "depl", id: "ebfc3f2a-54db-41ba-b9a2-982b6c2d4756"},
{date: 1584625891099, type: "depl", id: "696b15df-8f7d-42d5-af52-ec03b171c837"}]
var sort = myList.sort(function(x, y){
    return y.date - x.date;
})
console.log(sort)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...