'RXJS way to convert a string to an array of numbers
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]
Solution 1:[1]
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.
Solution 2:[2]
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 (in the case you want to notify each single number as a separate notification)
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.
If instead you want to notify just once the entire array of numbers, then the implementation would be the following
function fromNumericString(s: string) {
return new Observable((subscriber: Subscriber<number>) => {
const array = s.split(',').map(Number)
subscriber.next(array);
subscriber.complete();
});
}
Solution 3:[3]
Another option is to use from, which takes an array of items to emmit. Depending on how you got the source, this could be easier.
from('4,5,67,8'.split(',')).pipe(
map(Number)
)
As with other examples you could use map(parseInt), if the function takes one argument you don't need to pass it through an arrow function (just watch out for situations where there are optional arguments that could cause a problem).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Semi-Friends |
| Solution 2 | |
| Solution 3 | robmcm |
