Adding a value to an object array with reduce

Asked

Viewed 256 times

1

I have an array of objects that follow this format:

[
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];

I want to go through this array and get the sum of all the points on each vector item. How do I do this using Javascript reduce??

2 answers

2


Thus:

array.reduce((a, b) => a + b.points, 0)

Basically, what happens is that the function you pass by parameter to the reduce (a + b.points) will be executed for each item of the array.

The parameter a will receive the value of the last call result (if it is the first call it will receive the value of the second function parameter reduce - that 0).

The parameter b will receive every item from array.

Something like that:

1. Item do Array
a = 0
b = { name: 'Batata', points: 23 }
Retorno da função: 0 + 23

2. Item do array
a = 23
b = { name: 'Pizza', points: 50 }
Retorno da função: 23 + 50

3º Item do array
a = 73
b = { name: 'Tacos', points: 60 }
Retorno da função: 73 + 60

The function that you

See working:

var array = [
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];

var soma = array.reduce((a, b) => a + b.points, 0)
console.log(soma)

1

That way it would return an object with the sum:

var items = [
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];
const reducer = (a, b) => {
  return a.points += b.points, a;
}
const soma = items.reduce(reducer, {points: 0});

console.log(soma);


Other form used map to create only one array simple with values and used reduce to add:

var items = [
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];

const i = items
  .map(x => x.points)
  .reduce((a, b) => a + b, 0);
console.log(i);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.