0

In my typescript code (angular component) I need to populate an array and then sort it. However, the array doesn't sort? If I instead instantiate/populate the array "manually" it sorts as expected. What am I missing?

This works:

let chartArr: any = [];

chartArr = [
  {text: 'AA', assignedTasks: 3},
  {text: 'BB', assignedTasks: 7},
  {text: 'CC', assignedTasks: 1},
  {text: 'DD', assignedTasks: 10},
];

console.log(this.chartArr.sort((a, b) => b.assignedTasks - a.assignedTasks ));

This doesn't:

let chartArr: any = [];

 doc.forEach(user => {
        eventTasksRefCount = this.afs.collection('eventTask', ref => ref.where('uid', '==', user.uid));
        eventTasksObservableCount = eventTasksRefCount.valueChanges();
        eventTasksObservableCount.subscribe(result => {
        this.chartArr.push({text: user.displayName, assignedTasks: result.length });


        });

console.log(this.chartArr.sort((a, b) => b.assignedTasks - a.assignedTasks ));
JLRishe
  • 99,490
  • 19
  • 131
  • 169
Magnus Jonsson
  • 217
  • 2
  • 5
  • 12
  • 1
    You're displaying your array in a synchronous way, while you're fetching data in an asychronous way. –  Oct 02 '19 at 10:48
  • 1
    The sorting isn't working because you're sorting the array when it's empty. – JLRishe Oct 02 '19 at 10:51

1 Answers1

0

You have to sort the array inside your subscribe call, otherwise your data isn't ready if you sort it.

E.g:

let chartArr: any = [];

 doc.forEach(user => {
        eventTasksRefCount = this.afs.collection('eventTask', ref => ref.where('uid', '==', user.uid));
        eventTasksObservableCount = eventTasksRefCount.valueChanges();
        eventTasksObservableCount.subscribe(result => {
        this.chartArr.push({text: user.displayName, assignedTasks: result.length });
        console.log(this.chartArr.sort((a, b) => b.assignedTasks - a.assignedTasks ));
        });

But be careful now you always sort if some new result comes in, i don't know if this is intended.

Have a look at angulars observable guide for further details.

zerocewl
  • 11,401
  • 6
  • 27
  • 53