Julio Rodriguez
Julio Rodriguez

Reputation: 515

Omit action in "if" statement in JavaScript

I'm getting my hands dirty with Rxjs with some strings and objects in order to learn it.

I'm trying to dynamically create key/values in an empty declared object, using a string variable.

In this approach, what I want to do is the following: Iterate the whole string, including spaces and commas.

If a letter is already in the object, increment its value, otherwise, add it.

So I came up with the following piece of code:

https://stackblitz.com/edit/rxjs-js-letttesr-cool-commas-not-cool?file=index.js

Upvotes: 0

Views: 42

Answers (1)

Lievno
Lievno

Reputation: 1041

import { ReplaySubject, from } from "rxjs";
import { tap, reduce } from "rxjs/operators";

// string
const str =  "I am afraid I can not do that, Dave";
//string no spaces
let strNoSpace = str.replace(/\s+/g, ''); 

from(strNoSpace).pipe(
  reduce((acc, value) => {
    if(acc[value] !== undefined) {
      acc[value] = acc[value] + 1;
    } else {
      acc[value] = 1;
    }
    return acc;
  }, {}),
).subscribe(console.log);

stackblitz

Upvotes: 2

Related Questions