Home > Back-end >  Array iterating with` Rxjs` filter and map
Array iterating with` Rxjs` filter and map

Time:10-07

What is the correct way to iterate the array with map and filter? at present both expects the single value. but my Observable with array. please advice me the correct way.

here is my ts:

import { Component, OnInit } from '@angular/core';
import { Observable, of } from 'rxjs';
import { filter, map, tap} from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

  name = 'Angular';
  ranks:Observable<number[]>;
  rankList$:Observable<number[]>;

  constructor(){
    this.ranks = of([1,2,3,4,5]);
  }

  ngOnInit(){
    this.rankList$ = this.ranks.pipe(
      filter(n => n % 2 !== 0), map((num:number[]) => num)
      )
  }
}

getting an error as:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.(2362)
(parameter) n: number[]

Live Demo

CodePudding user response:

I think you are mixing between array filter and observable filter, observable filter will apply to the emitted value, in your case the entire number array, hence the error you are getting, observable filter will check items emitted to the observable and if the condition is true it will to continue the emission, if that's your goal, your condition in the observable filter should be applied to the item emitted type which is an array, but if you are trying to filter the emitted array and emit only Odd values, then map is what you should be using.

this.rankList$ = this.ranks.pipe(
  map((num: number[]) => num.filter(n => n % 2 !== 0))
);
  • Related