-1

Hi I'm trying to take value from an object and find the sum. I currently have an object of three values and properties and would like to take the numbers and would like to add them and store them

 public selectedItem = {name:" "}; // Separate Object that displays values. Dont want to display it just add the value

public shoppingListItems = [
      {name: "Milk" ,number: 100},
      {name: "Sugar", number: 22,},
      {name: "bread", number: 12}
    ]; 

 public Price = [];

this.Price.push(shoppingListItem.keys(this.selectedItem)); // Attempt to push my shopping list items onto the Price Array
     console.log(this.Price); // Check is the values are actually stored.

I have attempted to create a separate array and store the values there by doing the following so that I may push my number values onto my array but it does not seem to do so. Would there be a way to just take the values out of my object and add them to my array so that I may store them and potentially add them later?

Jlee
  • 17
  • 2
  • 9

1 Answers1

3

Look up using map to create a new array containing the values of a property of the objects in the original array and reduce to get the sum of those numbers.

Here's a simple example that you can apply to your scenario:

const shoppingListItems = [
    {name: "Milk", number: 100},
    {name: "Sugar", number: 22},
    {name: "bread", number: 12}
]; 

// creates an array of the `number` property: [100, 22, 12]
const numbers = shoppingListItems.map(i => i.number);
// gets the sum of the array of numbers: 134
const sum = numbers.reduce((a, b) => a + b, 0);
David Sherret
  • 101,669
  • 28
  • 188
  • 178