Home > Net >  RXJS way to convert a string to an array of numbers
RXJS way to convert a string to an array of numbers

Time:02-15

How do I do this in RXJS? I've tried froms, ofs, filters, maps...

const b = '4,5,67,8';
let bb = b.split(',');
for (let i = 0; i < bb.length; i  ){
  temp.push(Number(bb[i]));
}
console.log(temp) //[4, 5, 67, 8]

CodePudding user response:

you can just do it like this

of("4,5,67,8")
    .pipe(
      map((value) => value.split(",").map(Number))
    )
    .subscribe(console.log);

please be guided the the map inside the pipe is from rxjs/operator.

CodePudding user response:

The solution from @Semi-Friends seems the most straightforward.

You have also the opportunity to create a fancier one by building your own custom creation operator.

A creation operator is a function that can take some input and returns an Observable.

In this case a custom creation operator could look like this

function fromNumericString(s: string) {
  return new Observable((subscriber: Subscriber<number>) => {
    const array = s.split(',').map(Number)
    for (let i = 0; i < array.length && !subscriber.closed; i  ) {
      subscriber.next(array[i]);
    }
    subscriber.complete();
  });
}

and would be used like this

fromNumericString('1,2,3').subscribe(console.log)

See this stackblitz for more details/

CodePudding user response:

of('4,5,67,8').pipe(
map(stringOfNumbers => stringOfNumbers.split(',').map(num => parseInt(num))
).subscribe(console.log) //[4,5,67,8]
  • Related