0

There's an object holding items and prices from a grocery store:

let groceryStore = {
    'Banana' : .25,
    'Apple' : .30,
    'Lettuce' : 1.20,
    'Onion' : .15,
    'Celery' : 1.15,
    'Garlic' : 1.00,
    'Tomato' : .50
}

You have an array of keys:

let groceryList = ['Tomato', 'Lettuce', 'Garlic', 'Onion']

I now need to find the total of all the values to the keys in my array(groceryList).

1 Answer 1

2

To take an array, and reduce it to another values, you can usually use the aptly named Array.reduce(). Usually to sum an array of numbers, you reduce the array, and add each number to the accumulator (sum in the example):

arrayOfNumbers.reduce((sum, num) => sum + num, 0)

In your case, reduce the array of keys, and take the values from the object using the key:

const groceryStore = {
  'Banana': .25,
  'Apple': .30,
  'Lettuce': 1.20,
  'Onion': .15,
  'Celery': 1.15,
  'Garlic': 1.00,
  'Tomato': .50
}

const groceryList = ['Tomato', 'Lettuce', 'Garlic', 'Onion']

const result = groceryList.reduce((sum, key) => sum + groceryStore[key], 0)

console.log(result)

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

1 Comment

Like a charm. Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.