Search code examples
javascriptangularreduce

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


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; 
}

Solution

  • 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);