var groceries = [
{
id: 1,
product: 'Olive Oil',
price: '$' 12.1
},
{
id: 2,
product: 'Tomato Soup',
price: '$' 3.48
},
{
id: 3,
product: 'Cheesecake',
price: '$' 17.36
},
{
id: 4,
product: 'Sirloin Steak',
price: '$' 14.8
},
{
id: 5,
product: 'Brie Cheese',
price: '$' 23.28
}
];
var sum = _.reduce(products, function (total, price) {
return total price;
}, 0);
I'm not so sure how to remove the '$' from the price before we starting adding the values up. I've tried my best to look for other solutions here (I'm new), but there seems to be only examples where "price" are only numbers.
Sorry if this a similar problem already been posted somewhere else, but am still learning how to navigate here, and I have yet to find a similar situation unless someone can point me to it!
CodePudding user response:
In the code, the price
that you currently use is the object for every iteration with the properties from the array. Instead, you could take the price property from the object.
In your example data, there are only leading $
that you could remove from the price property. Then you can use for example parseFloat and only add the value if the conversion does not yield NaN.
Then pass the groceries
variable to reduce instead of products
which is not present in the example code.
Note that currently we are adding values of the same currency, and if you have different currencies you have have to account for that when calculating the sum.
var groceries=[{id:1,product:'Olive Oil',price:'$' 12.1},{id:2,product:'Tomato Soup',price:'$' 3.48},{id:3,product:'Cheesecake',price:'$' 17.36},{id:4,product:'Sirloin Steak',price:'$' 14.8},{id:5,product:'Brie Cheese',price:'$' 23.28},{id:6,product:'Product with invalid price',price:'$' "hello"}];
var sum = _.reduce(groceries, function (total, obj) {
var price = parseFloat(obj.price.replace(/^\$/, ''));
if (!isNaN(price)) {
return total price;
}
return total;
}, 0);
console.log(sum)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here, I have used Javascript's default function reduce
for getting the cumulative sum.
var groceries = [
{
id: 1,
product: 'Olive Oil',
price: '$' 12.1
},
{
id: 2,
product: 'Tomato Soup',
price: '$' 3.48
},
{
id: 3,
product: 'Cheesecake',
price: '$' 17.36
},
{
id: 4,
product: 'Sirloin Steak',
price: '$' 14.8
},
{
id: 5,
product: 'Brie Cheese',
price: '$' 23.28
}
];
//reduce((total, currentIteratedValue) => {}, initialCumulativeValue)
//Initially we take sum as 0
const sum = groceries.reduce(function (currentTotal, obj) {
var price = parseFloat(obj.price.slice(1));
if (!isNaN(price)) return currentTotal price;
return currentTotal;
}, 0);
console.log(sum)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>