Home > other >  How to sort data retreived from ngrx-entities
How to sort data retreived from ngrx-entities

Time:09-01

I have to sort data fetched from the ngrx-entities-store. I'm not intending to do it inside the reducer because I have three sorting methods to implement and I followed the accepted answer on this stackoverflow post to try to make it done, but I'm kinda hitting the walls. The unsorted data are well fetched using this snippet:

sortPersnlByFunction(sortBy: string){
    this.filterDefault = false;
    this.filterByStatus = false;
    this.filterByFunction = true;
    this.zone.run(() => {
    this.store
      .pipe(select(selectAllPrsnls), map((prsnlList) => prsnlList))
      .subscribe(value => {
        this.Prsnl = Object.entries(value[1]).map((e) => ( e[1]  ));
        console.log("The Prsnl", this.Prsnl)
    });   
  })}

The console shows that the data (not sorted) is successfully fetched, and I then added this fragment to perform the sorting:

this.sortedPrsnl = [...this.Prsnl].sort(
          (a, b) => a[sortBy].localCompare(b[sortBy]));

Now the overall code is like this:

sortPersnlByFunction(sortBy: string){
    this.filterDefault = false;
    this.filterStatus = false;
    this.filterFunction = true;
    this.zone.run(() => {
    this.store
      .pipe(select(selectAllPrsnls), map((prsnlList) => prsnlList))
      .subscribe(value => {
        this.Prsnl = Object.entries(value[1]).map((e) => ( e[1]  ));
        this.sortedPrsnl = [...this.Prsnl].sort(
          (a, b) => a[sortBy].localCompare(b[sortBy]));
        console.log("The sorted", this.sortedPrsnl)
    });
    
  })}

But adding the sorting fragment does not work either, nor the console.log method triggered. It seems like the last fragment failed to execute, and so the console.log wasn't even reached to display anything at all.

I just want to mention that the sortBy is a criteria string sent from the frontend, and is the keyword by which the sorting should be applied to. It's a Prsnl data property. I'm gratefull to any help to make this done, thanks in advance.

CodePudding user response:

Since the last console.log is not showing anything, you know that your fragment

this.sortedPrsnl = [...this.Prsnl].sort(
          (a, b) => a[sortBy].localCompare(b[sortBy]));

is not working. And a possible raison for that is because the sortby parameter is not used, and can not be used that way. So I will suggest to you another approach to avoid confusion. instead of localeCompare go ahead and compare the elements yourself, with javascript basic string comparison operators. Then, assuming that myField is the filed property you wanted to sort with, your fragment will become this:

this.sortedPrsnl = [...this.Prsnl].sort(
              (a, b) => (a.myField.toLowerCase() > b.myField.toLowerCase())? 1 : -1;

With this approach you sort this.Prsnl in alphabetic order of field myField which should be a field property of this.Prsnl.

  • Related