Search code examples
javascriptangularrxjsrxjs-pipeable-operatorsngx-charts

groupBy based on range of values using RxJS in angular


I have a raw data array

[
  {bugid: b1 , state: 'foo', days: 2}, 
  {bugid: b2, state: 'bar', days: 41}, 
  {bugid: b3, state: 'foo', days: 45}
]

I want to group this data using RxJS in this format

{
  '0-25': [{ name: foo, value: 1}, {name: bar, value: 0}], 
  '26-50': [{name: foo, value: 1}, {name: bar, value: 1}]
}

I am not able to group in the range


Solution

  • You don't need rxjs for this.

    const data = [
      { state: 'foo', days: 2 }, 
      { state: 'bar', days: 41 }, 
      { state: 'foo', days: 45 }
    ];
    
    // get all possible states
    const states = [...new Set(data.map(item => item.state))];
    
    const result = {
      '0-25': getCounts(0, 25),
      '26-60': getCounts(26, 50)
    };
    
    function getCounts(from, to) {
      return states.map(state => ({ name: state, value: getValue(state, from, to) }));
    }
    
    function getValue(state, from, to) {
      return data.filter(item => item.state === state && item.days >= from && item.days <= to).length;
    }