1

I have the following values in an array which I am trying to get the sum of it. This is how it looks like from the chrome developer tools

(3) [{…}, {…}, {…}]0: {ID: 1, ProductName: " New phone 1", Price: "€ 600"}1: {ID: 3, ProductName: " New phone 2", Price: "€ 1000"}2: {ID: 4, ProductName: " New phone 3", Price: "€ 400"}length: 3__proto__: Array(0)

I would like to get the prices of each Item and compute a sum of all the values. I getting these values from an Api and it could sometimes be more items or less. Currently this is how I am getting the values

function setTotalPrice() {
    fetch("http://localhost:1234/api/Product")
        .then(response=>response.json())
        .then(data => {
            data.forEach(element => {
                console.log(element.Price)
            });
        })
}

3 Answers 3

3

You need to get the number from the Price string (split) and sum them using reduce

const data = [
    { ID: 1, ProductName: 'New phone 1', Price: '€ 600' },
    { ID: 3, ProductName: 'New phone 2', Price: '€ 1000' },
    { ID: 4, ProductName: 'New phone 3', Price: '€ 400' },
];

const result = data.reduce((acc, val) => acc + parseInt(val.Price.split(' ')[1], 10), 0);

console.log(result);
console.log('€ ' + result);

If API can return a floating point number for Price, need to use parseFloat instead:

const data = [
    { ID: 1, ProductName: 'New phone 1', Price: '€ 600.25' },
    { ID: 3, ProductName: 'New phone 2', Price: '€ 1000' },
    { ID: 4, ProductName: 'New phone 3', Price: '€ 400.10' },
];

const result = data.reduce((acc, val) => acc + parseFloat(val.Price.split(' ')[1]), 0);

console.log(result);
console.log('€ ' + result);

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

1 Comment

why not parseFloat?
0
const sum = data
  .map(({ price }) => {
    const digitsStartIndex = price.substring(price.findIndex(' ') + 1);
    return parseFloat(digitsStartIndex, 10)
  })
  .reduce((a, b) => a + b, 0)
console.log(`€ ${sum}`)

Comments

0

You could use reduce with a little bit of regex /\d+/

let data = [
    { id: 1, product: 'phone 1', price: '€ 400' },
    { id: 3, product: 'phone 2', price: '€ 3000' },
    { id: 4, product: 'phone 3', price: '€ 600' },
];

let sum = data.reduce((a,{price}) => a + Number(price.match(/\d+/)),0);

console.log(sum);

Comments

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.