0

How can i use parseFloat when data lives inside of an array?

Let's say that i get an api response like this:

$scope.response = [{name: "Richard", qty: "350.99"},
{name: "Chuck", qty: "199"},
{name: "Phonenix", qty: "233.77"}]

I want to sum the values of qty, but i cannot 'cause the data type. If i need to use parseFloat over qty, how can i get only those values?

I have to use something like some() to get qty values?

I'm using AngularJs and Javascript.

2
  • reduce it to return a sum. $scope.response.reduce((a,b) => a + parseFloat(b.qty)); Commented Jan 10, 2018 at 17:48
  • Thanx again. Just missing the ,0); Commented Jan 10, 2018 at 18:10

4 Answers 4

3

You can iterate over the Array and calculate the sum using Array.reduce

const arr = [{
    name: "Richard",
    qty: "350.99"
  },
  {
    name: "Chuck",
    qty: "199"
  },
  {
    name: "Phonenix",
    qty: "233.77"
  }
];

const result = arr.reduce((sum, current) => {
  return sum + parseFloat(current.qty);
}, 0);

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

You don't need to do the reassignment sum += since reduce passes the return value to each iteration you can just add them together
2

Use array#reduce to sum all qty of response array.

var response = [{name: "Richard", qty: "350.99"},{name: "Chuck", qty: "199"},{name: "Phonenix", qty: "233.77"}],
    result = response.reduce((sum, {qty}) => sum += +qty, 0);

console.log(result);

1 Comment

This is cool, I like the destructuring. But isn't the reassignment sum += qty unnecessary when you can just add them together like sum + qty?
2

You could use reduce for this:

const response = [
  {name: "Richard", qty: "350.99"},
  {name: "Chuck", qty: "199"},
  {name: "Phonenix", qty: "233.77"}
];

const sumQuantities =
  response.reduce((acc, x) =>
    acc + parseFloat(x.qty)
  , 0);
    
console.log(sumQuantities);

Comments

2

You can map the array to return the parseFloat of the qty, then use reduce to add the values.

var response = [{
    name: "Richard",
    qty: "350.99"
  },
  {
    name: "Chuck",
    qty: "199"
  },
  {
    name: "Phonenix",
    qty: "233.77"
  }];

var sum = response.map(function(obj) {
    return parseFloat(obj.qty);
  })
  .reduce(function(a, b) {
    return a + b;
  }, 0);
  
console.log(sum)

2 Comments

don't forget the default value to reduce as 2nd param
Great catch @RaphaMex. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.