0

I set up pipeline for sorting. It is sorting but I got this type of error:

cannot read properties of undefined (reading 'sort')

in angular core.js in my local running.

Here is my order-by.pipe.ts

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

@Pipe({
  name: 'orderBy',
})
export class OrderByPipe implements PipeTransform {
  transform(array: any, field: string): any[] {
    array.sort((a: any, b: any) => {
      if (a[field] < b[field]) {
        return -1;
      } else if (a[field] > b[field]) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }
}
1
  • you could also do a console.log before array.sort to check what value is coming inside the array Commented Sep 8, 2021 at 3:58

1 Answer 1

1

You need to check that array must have value then only proceed for sorting.

Meanwhile, you should specify array as any[] type as sort() is a method provided by Array.

Solution 1

Straight break the function when array is nullish (null or undefined).

transform(array: any[], field: string): any[] {
  if (!array) return array;

  array.sort((a: any, b: any) => {
    if (a[field] < b[field]) {
      return -1;
    } else if (a[field] > b[field]) {
      return 1;
    } else {
      return 0;
    }
  });

  return array;
}

Sample Solution 1 on StackBlitz


Solution 2

Use Typescript optional chaining so that .sort() will not be executed when array is nullish (null or undefined).

transform(array: any[], field: string): any[] {
  array?.sort((a: any, b: any) => {
    if (a[field] < b[field]) {
      return -1;
    } else if (a[field] > b[field]) {
      return 1;
    } else {
      return 0;
    }
  });
  
  return array;
}

Sample Solution 2 on StackBlitz

Sign up to request clarification or add additional context in comments.

3 Comments

I got type error TypeError: Cannot assign to read only property '0' of object '[object Array]' for [items]="buildings$ | async | orderBy: 'buildingName'"
Hi, looks like the issue you faced is extension / not linked with this question. I would suggest you create a new question by providing a Minimal, Reproducible Example. Looking forward to your question.
Thanks Yong Shun. I just found the answer which is create copy of array before sorting it transform(array: any[], field: string): any[] { if (!array) return array; array = [...array]; array.sort((a: any, b: any) => { if (a[field] < b[field]) { return -1; } else if (a[field] > b[field]) { return 1; } else { return 0; } }); return array; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.