简体   繁体   中英

How to assign sorted data to immutable object

I am getting data from ngrx/store this data is sorted in front end. when the data sorted, i am assigning back to value, but no update happening. I understood that the data is immutable . But how to assign the value back to immutable ?

here is my try: this.data - not updated after sort.

this.data = this.data.slice().sort((a, b) => {
  if (this.sort) {
    if (isNaN(a)) {
      if (a[sortBy] < b[sortBy]) {
        return -1;
      }
    }
    if (!isNaN(a)) {
      return a[sortBy] - b[sortBy];
    }
  }
  if (!this.sort) {
    if (isNaN(a)) {
      if (b[sortBy] < a[sortBy]) {
        return -1;
      }
    }
    if (!isNaN(a)) {
      return b[sortBy] - a[sortBy];
    }
  }
});

In such scenarios you can use a sortBy Pipe . Below is a code that will help you out. The below code is capable of handling arrays of numbers, string, objects You can pass a key on which the sort needs to be applied. Also you can sort in reverse order if required.

Also this way you need not to modify your data and reassign. The pipe and angular will take care of sorting based on the inputs passed and same will be displayed on the UI. And you can use this Pipe across your code.

import {
  Pipe,
  PipeTransform
} from "@angular/core";

@Pipe({
  name: "sortBy"
})
export class ArraySortByPipe implements PipeTransform {
  public transform(array: any[], reverse: boolean = false, prop ? : string) {
    if (!Array.isArray(array)) {
      return array;
    }
    if (array.length) {
      let sortedArray: any[];
      if (typeof array[0] === "string") {
        sortedArray = array.sort();
      }
      if (typeof array[0] === "number") {
        sortedArray = array.sort((a, b) => a - b);
      }
      if (typeof array[0] === "object" && prop) {
        sortedArray = array.sort((a, b) => a[prop].toString().localeCompare(b[prop].toString()));
      }
      return !reverse ? sortedArray : sortedArray.reverse();
    }
    return array;
  }
}

Hope this helps :). Let me know if you still face any issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM