0

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

1 Answer 1

2

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))
);
Sign up to request clarification or add additional context in comments.

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.