JavaScript Reduce Method

JavaScript Reduce Method

The JavaScript reduce method takes each value of an array, and applies reducer function such that it changes the array into a single value.

Syntax of .reduce() method:

array.reduce((accumulator, currentValue, index, array) =>{....}, initialValue}

The .reduce() method takes two arguments :

  1. The first is reducer function, which is used to make the operation on the array. It also takes four arguments:(accumulator, current value, index, array)
    • Accumulator : It is the value reduce method returns after the last call of the reducer function.
    • Current value : It is the current value of the given array which is being processed.
    • Index : It is the index of the current value in the given array.(Optional)
    • Array : It is an array the reduce method was called on.(Optional)
  1. The second argument of reduce method is Initial value, it is the value where you want the reduce method to start. If you omit to pass initial value, then the reduce method will use first element of the array as the initial value.(Optional)

Example:

1) Subtract the numbers in array, from left to right.

const numbers = [150, 50, 25];
console.log(
  'Final result: ',
  numbers.reduce((accumulator, currentValue) => accumulator - currentValue)
);

Output:

Final result: 75

2) Count the occurrences on the basis of division, from the array of objects.

const testobjects = [
  { name: 'Sam', division: 'A' },
  { name: 'Jiza', division: 'B' },
  { name: 'Lisa', division: 'B' },
  { name: 'Joel', division: 'C' },
  { name: 'Bob', division: 'A' }
];
const occurrence = testobjects.reduce((accumulator, currentValue) => {
  const i = currentValue.division;
  if (i in accumulator) {
    accumulator[i] = accumulator[i] + 1;
  } else {
    accumulator[i] = 1;
  }
  return accumulator;
}, {});
console.log(occurrence);

Output:

{ A: 2, B: 2, C: 1 }

Read more

Automating a Scalable Command, Query and Event Package Structure with a Batch Script

Automating a Scalable Command, Query and Event Package Structure with a Batch Script

Introduction As backend applications grow, maintaining a consistent project structure becomes increasingly important. In a small application, developers can manually create packages and folders whenever a new business entity or feature is introduced. However, in a larger application following architectural patterns such as CQRS, Domain-Driven Design, and event-driven architecture, every

By Sangram Ekshinge