Issue
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!
Solution
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)
Answered By - Himanshu Singh Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.