[how-to] Use _.sum() on an array

User sometimes are unable to use the lodash function _.sum() onto their data to get the sum of an array. This can be due to data being returned back as a string and not an integer. This results in user's seeing their JS returning all their numbers combined together into a single number-string instead the of the sum of all values in the array.

Expect response to be 6, but instead got "123":

Solution:
In order to add the numbers together, we need to make sure the number-string is a turned into an integer. We can use the parseInt() method onto the values in the array.

let data = ["1", "2", "3"]

let result = data.map(string => {
  return parseInt(string) // 'result' will now equal [1, 2, 3] with each value as an integer
})

return _.sum(result) // 6

1 Like