-1

so im trying to find a more efficient way to write the following code.

cartState.forEach((cart) => subTotal += cart.price);

I feel like if cartState is quite large, and becuase each cart object is quite large in itself. so purely performance or best practices is there a better way to do this?

Heres the array

const cartState = [
    {
      name: 'xxx',
      price: 'xxx',
    },
]

Just as an edit, this isn't just for adding totals, it's also for combining values into an array.

  • 1
    Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Viet Dinh Oct 14 '20 at 17:32
  • In this particular case yeah, but i will also be using it for adding values into an array if they're not numbers ie ```cartState.forEach((cart) => items.push(name));``` – Nathan Leadill Oct 14 '20 at 17:45
  • You need to go through each object and access a property one way or the other. – adiga Oct 14 '20 at 17:50

1 Answers1

1

By efficient did you mean the fastest computation time or readability? If you want the fastest solution, try a for loop, because all the other options i.e. map/reduce/forEach are much slower than for loop. You can find here.

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30