🫐Reducing arrays of objects

The Array.prototype.reduce() method in JavaScript is a higher-order function that takes an array of values and combines them into a single value. It does this by applying a function to each element in the array, and using the return value of that function as an accumulator.

Here is an example of using reduce() to add up the values in an array of numbers:

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // 10

In this example, the reduce() function is called on the numbers array with two arguments: a callback function and an initial accumulator value of 0. The callback function has two arguments: accumulator and currentValue.

On the first iteration, accumulator is set to 0 (the initial value) and currentValue is set to 1 (the first element in the array). The callback function returns 0 + 1, which is then used as the accumulator in the next iteration. On the second iteration, accumulator is set to 1 (the result of the previous iteration) and currentValue is set to 2 (the second element in the array). This process continues until all elements in the array have been processed, and the final value of accumulator is returned.

You can also use reduce() to reduce an array of objects. For example, let's say you have an array of objects that represent employees, and each object has a name and a salary property. You can use reduce() to calculate the total salary for all employees:

const employees = [
  { name: 'John', salary: 50000 },
  { name: 'Sara', salary: 60000 },
  { name: 'James', salary: 40000 }
];

const totalSalary = employees.reduce((accumulator, employee) => accumulator + employee.salary, 0);

console.log(totalSalary); // 150000

In this example, the callback function takes two arguments: accumulator and employee. On each iteration, accumulator is set to the result of the previous iteration, and employee is set to the current element in the array. The callback function adds the salary property of the employee object to the accumulator, and the final value of the accumulator is returned as the total salary for all employees.

Last updated