Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count and add the values of keys in a object

Tags:

javascript

I need to write a function that takes in 2 arguments, the first argument is a list of <li> elements and the second argument is an object. The object is list of products and their prices. All the <li>elements will have text containing a name of a product.The function should check the price of each product mentioned, calculate and return the total price.

Example:

<ul>
    <li>oreos<li/>
    <li>milk<li/>
<ul/>
let products = {
    oreos: 20,
    milk:  17,
    bread: 12,
    doritos: 10
}

I have tried using a for in/of loop to go through the products object and match it to the <li> using .innerText but am unsure of how to go about doing it.

Please help out

like image 327
muhammad Avatar asked Sep 14 '25 17:09

muhammad


2 Answers

What you can do is that, you can use the following function:

let totalPrice = (priceList, products) => {
return products.reduce((total, elem) => {
    total += priceList[elem.innerText];
    return total;
}, 0)

}

This function iterates on list of products using Array.reduce and adds the list of product prices and returns the total.

You should checkout Array.reduce() for more clarity.

like image 119
Safeer Raees Avatar answered Sep 16 '25 05:09

Safeer Raees


Here's what your function could look like:

  1. Iterate over all list items
  2. Get the text content of the item
  3. look up the price in the products object by using the text content as key
  4. add to the total
  5. return the total

I used Array.from() and Array.prototype.reduce() to achieve this all in one go. Of course you'd need a distinct class or even better an ID on the list instead of simply selecting all list items on the page.

let products = {
    oreos: 20,
    milk:  17,
    bread: 12,
    doritos: 10
}

function getTotal(listElements, productPrices) {
  var total = Array.from(listElements).reduce(function(total, listItem) {
    total += productPrices[listItem.textContent] || 0;
    return total;
  }, 0);
  return total;
}

console.log(getTotal(document.querySelectorAll('li'), products));
<ul>
    <li>oreos</li>
    <li>milk</li>
</ul>
like image 20
Constantin Groß Avatar answered Sep 16 '25 06:09

Constantin Groß