PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] how to reduce an array of objects of stringed price

 July 21, 2022     integer, javascript, reduce, string     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing