Is it possible to have two accumulators with the reduce method?

49 views Asked by At

Is it possible to have two accumulators with the reduce method? I need to pass another const inside my reduce. I want to do the same as const one with const two. Do I have to create a new method or can I pass it on here? If not then can I do it in a new method and pass it to this method for example?

method(items: any[]): Element[] {
        const xyz: { [key: string]: any[] } = items.reduce(
            (acc, line) => {
                // some code
                        const one = item.title;
                        const two = item.asset;
                        this.arr = [...this.arr, two];
                        acc[arr] = [...(acc[arr] || []), item];
                        return acc;
                    }
                }
            },
            {}
        );
const sets: Item[] = Object.entries(value).map(
   ([title, list]) => ({ 
     list, title, 
}) ); 
return sets; 
}
2

There are 2 answers

0
jeremy-denis On

The reduce function took only one acc parameter but you can imagine a structure where you store the different values

const array = [
  0, 1, 2, 3, 4, 5, 6
];

const result = array.reduce((acc, elem) => {
  acc.firstAcc += elem;
  if (elem % 2) {
    acc.secondAcc += 1; 
  }
  
  return acc;
}, {firstAcc: 0, secondAcc: 0});

console.log(result);

0
Daniel Hakobyan On

No, accumlator is a single argument of reduce method. Accumlator can have any format so you can use it as you like, for example create a structure where you can pass more than one value.

Also read the documentation

Inform me please if it helps