2

I want to sort the array and to store the fetched values into a new array for print. I tried with push() but there is an error is occurring and shows that" Cannot read property 'push' of undefined".

`

this.dataService.userprofile().subscribe((data:any) => {
      let profile:any[]=data.profiles;
      for(let index=0;index<profile.length;index++) {
        const element = profile[index];  
        const today: number = Date.now();
        var b = Math.abs(today - Date.parse(element["dob"]));
        element["dob"] = Math.floor(b / (1000 * 3600 * 24 * 365.25));
        if (element["active"]=="N"){
          this.row.push(element); 
        }}
      this.rowData = this.row;//ag-grid row
      console.log(this.rowData)
    })

`

3
  • 4
    Is this.row initialized in any way in the context of your function ? Commented Jan 10, 2019 at 2:39
  • this.row = (this.row || []).concat(element); Commented Jan 10, 2019 at 2:51
  • @Paqman i think row is a local variable to store the array of elements and populate the initialized this.rowData.. In my answer i suggest to work directly with this.rowData assigning the result of Array.prototype.reduce() Commented Jan 10, 2019 at 4:03

2 Answers 2

2

Instead of using for loop that it is hard to read and maintain you better use Array.prototype.reduce() and using the dot notation

Also notice that in TypeScript you should avoid using type any

Code:

this.dataService.userprofile().subscribe((data: any) => {
  this.rowData = data.profiles.reduce((acc, element) => {
    const b = Math.abs(today - Date.parse(element.dob));
    element.dob = Math.floor(b / (1000 * 3600 * 24 * 365.25));
    return element.active == 'N' ? [...acc, element] : acc;
  }, []);

  console.log(this.rowData)
});
Sign up to request clarification or add additional context in comments.

Comments

0

Declare row variable before for loop.

this.dataService.userprofile().subscribe((data:any) => {
      let profile:any[]=data.profiles;
      let row = [];
      for(let index=0;index<profile.length;index++) {
        const element = profile[index];  
        const today: number = Date.now();
        var b = Math.abs(today - Date.parse(element["dob"]));
        element["dob"] = Math.floor(b / (1000 * 3600 * 24 * 365.25));
        if (element["active"]=="N"){
          row.push(element); 
        }}
      this.rowData = row;//ag-grid row
      console.log(this.rowData)
    })

Comments

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.