btroncone / learn-rxjs

Clear examples, explanations, and resources for RxJS

Home Page:https://www.learnrxjs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

GroupBy example

sant123 opened this issue · comments

The example of groupBy uses .flatMap(group => group.reduce((acc, curr) => [...acc, curr], [])). Is it not better to use .flatMap(group => group.toArray())? Or does it have a performance impact? This is the full code:

const Rx = require("rxjs");

const people = [{ name: 'Sue', age: 25 }, { name: 'Joe', age: 30 }, { name: 'Frank', age: 25 }, { name: 'Sarah', age: 35 }];
//emit each person
const source = Rx.Observable.from(people);
//group by age
const example = source
    .groupBy(person => person.age)
    //return as array of each group
    .flatMap(group => group.toArray())
    // .flatMap(group => group.reduce((acc, curr) => [...acc, curr], []))
    /*
      output:
      [{age: 25, name: "Sue"},{age: 25, name: "Frank"}]
      [{age: 30, name: "Joe"}]
      [{age: 35, name: "Sarah"}]
    */
const subscribe = example.subscribe(console.log);

Thank you!

@sant123 Good find, I think either will work perfectly fine but your version is more clear. I will update the example accordingly, thanks! 👍

Great! 😃

Thanks to you!

Updated 👍