All Articles

Return A Single Numeric Value From An Array Of Objects In JavaScript


Problem

Summary

You have an array of objects.

You want to return a single numeric value based on some logic that should apply to each object in the array.

Let’s say you want to calculate profit from a series of individual bets:

const betResultsArray = [{
  won: true,
  stake: 10,
  odds: 2
}, {
  won: false,
  stake: 10,
  odds: 7
}, {
  won: false,
  stake: 10,
  odds: 4.2
}, {
  won: true,
  stake: 10,
  odds: 7.5
}, {
  won: true,
  stake: 10,
  odds: 4.3
}]

Solution

Use Array.prototype.reduce to iterate and reduce to a single value:

const totalProfit = betResultsArray.reduce((a, b) => {
  //  If the bet didn't win, subtract your bet stake from your current balance
  if (!b.won) {
    return a - b.stake
  }

  // Calculate profit
  const profit = (b.stake * b.odds) - b.stake

  // Add profit to you current balance
  return a + profit
}, 0)

In this example:

  • We start by passing in 0 as the 2nd argument to the reduce callback, this signifies a starting profit of 0
  • We loop through every object in the array and use the information on the subsequent bet object (b) to determine what is added to, or subtracted from, our previous value (a)
  • If the bet has won, we add our profit to the existing value, else, we subtract the stake from our existing value
  • The returned result at the end is our overall profit, after all items in the loop have been evaluated

That is to say, we run 0 (starting value) + ((10 * 2) - 10) (first item in the array, wons) - 10 (second item loses), and so on.

We now have one numerical value returned from an array of objects.

Problem Solved

If you have any questions you’d like to ask me about this post, feel free to reach me on Twitter or Github.

If you found this post useful and would like to show you’re appreciation, explore the links in the sidebar :)