How to use reduce in an object array in React

Asked

Viewed 392 times

1

import React from 'react';

const App = () => {

  const fruits = [
        { name: "banana", cor: "yellow", price: 2 },
        { name: "cherry", cor: "red", price: 3 },
        { name: "strawberry", cor: "red", price: 4 },
      ]
  

  return (
    <div className="App" >
      <div id="all fruit names"></div>
      <div id="red fruit names"></div>
      <div id="total"></div>
    </div>
  );
}

I need to add up the value of fruit prices, but I’m not getting the value of the object. When I use map it returns the numbers but in the form of string.

3 answers

2

Initially I recommend a reading on How to Not Ask Questions in Stack Overflow, I will answer the same according to what I understood by the title of the question using the method reduce to add the values in the desired array.

const fruits = [
  { name: "banana", cor: "yellow", price: 2 },
  { name: "cherry", cor: "red", price: 3 },
  { name: "strawberry", cor: "red", price: 4 },
];

// acumulador é a variável que mantem o valor da soma dos seus items, que neste caso começa de 0 e a cada iteração é somado o valor o objeto atual
const result = fruits.reduce(function (acumulador, objetoAtual){
  return acumulador + objetoAtual.price;
}, 0);

// Este irá produzir o mesmo resultado porem usando uma Arrow Function
const result2 = fruits.reduce((a, b) => a + b.price, 0);

console.log(result);
console.log(result2);

1

I know the question is how to use reduce (and another answer already explained how to do it), but in fact you don’t need it. A loop simple already solves:

let total = 0;
for (const fruit of fruits) {
    total += fruit.price;
}
// usar o total do jeito que quiser

Or the for more traditional:

let total = 0;
for (let i = 0; i < fruits.length; i++) {
    total += fruits[i].price;
}

That’s all.


"Ah, but I want use reduce."

What for? Do you really need it? Unless they’re "forcing" you, I don’t see any technical or practical reason to use it instead of a loop simple (except perhaps for personal taste, or "good practice", or "functional paradigm is cooler", etc). Perhaps you are told that it is "better because it has fewer lines":

let total = fruits.reduce((a, b) => a + b.price, 0);

But "smaller code" is not necessarily "better". Not least because reduce generally will be slower than a for simple (of course for a few small arrays, the difference will be insignificant and imperceptible, but increase their size and the difference becomes evident).


Just to make it clear that I am not against the use of reduce in itself. I just think it’s "overvalued", and it’s not always necessary (to sum up elements of an array, I definitely find it an exaggeration).

0

Use map over an array to create a list of components for each item.

Use filter to filter an array according to a certain criterion. For example, to list only the red fruits.

Use reduce to transform an array into a value, which can be a number, an object, etc. In this case, to transform a list into a price total.

Optionally use React.useMemo to store a calculation, in case of re-rendering, redoing it only if the dependencies list changes.

Demo in the codesandbox

const Component = ({ fruits }) => {
  const redFruits = useMemo(() => fruits.filter(item => item.cor === "red"), [
    fruits
  ]);

  const total = useMemo(() => fruits.reduce((a, b) => a + b.price, 0), [
    fruits
  ]);

  return (
    <div className="App" style={{ border: "2px solid black" }}>
      <div id="all-fruit-names">
        {fruits.map(item => (
          <p>
            {item.name} ({item.price})
          </p>
        ))}
      </div>

      <div id="red-fruit-names" style={{ color: "red" }}>
        {redFruits.map(item => (
          <p>{item.name}</p>
        ))}
      </div>

      <div id="total">Total: {total}</div>
    </div>
  );
};

Browser other questions tagged

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