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
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.
Here's what your function could look like:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With