0

I understand that for count an array in Angular with rxjs I use reduce, for example if I want count : [{id: 1, items: [10, 20, 30]}] I use the following code:

const item = from([{id: 1, items: [10, 20, 30]}]);
item.pipe(
  map(actions => actions.items),
  mergeAll(),
  reduce((acc, i) => acc + i, 0)
).subscribe(p => console.log('Print 60: ', p)); 

The questions is How get make a reducer in the following array:

const items = [
{
  id: 1,
  boxing: [1, 2, 2]
},
{
  id: 2,
  boxing: [10, 10, 20]
}]; 

result expected:

[{
  id: 1,
  boxing: 5
},
{
  id: 2,
  boxing: 40
}]

I will appreciate your help

2
  • Any reason you're doing it inside of an rxjs stream? It seems since you have an array, you can just use the native .reduce function. Commented Jun 4, 2019 at 3:09
  • 1
    Hi jesse, no special reason, but the idea is to do it with rxjs. Thanks Commented Jun 4, 2019 at 3:24

2 Answers 2

6

You can easily do this with javascript by using reduce and map as

const items = [
     {id: 1, boxing: [1, 2, 2]},
     {id: 2, boxing: [10, 10, 20]}
];

let reducedItems = items.map(val => {
  return {
    id: val.id,
    boxing: val.boxing.reduce((a, i) => a + i)
   }
});

console.log(reducedItems);

Sign up to request clarification or add additional context in comments.

2 Comments

Alright @Jesse. I think you should post it as an answer
stackblitz.com/edit/rxjs-cxhrt9 Just a small example applying @Saksham example inside the pipe map()
1

One approach can be this.

from(items).pipe(
  mergeMap((data) => from(data['boxing']).pipe(
    reduce((acc, x) => acc + x),
    map((val) => { data['boxing'] = val; return data })
  )),
  toArray()
).subscribe((val) => console.log(val));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.