Building an E-Commerce Store - Browsing Products Chapter 10
The price is going to be a little more complicated to work out. This is because each variation
on the product can have a different price, however, these are often the same. If there are
different prices we should display the cheapest one with a from prepended.
We need to create a function that loops through the variations and works out the cheapest
price and, if there is a price range, add the word from. To achieve this, we are going to loop
through the variations and build up an array of unique prices – if the price does not already
exist in the array. Once complete, we can check the length – if there is more than one price,
we can add the prefix, if not, it means all variations are the same price.
Create a new method on the ListProducts component called productPrice. This
accepts one parameter, which will be the variations. Inside, create an empty array, prices:
productPrice(variations) {
let prices = [];
}
Loop through the variations and append the price to the prices array if it does not exist
already. Create a for loop that uses the includes() function to check if the price exists in
the array:
productPrice(variations) {
let prices = [];
for(let variation of variations) {
if(!prices.includes(variation.price)) {
prices.push(variation.price);
}
}
}
With our array of prices, we can now extract the lowest number and check whether there is
more than one item.
To extract the lowest number from an array, we can use the JavaScript Math.min()
function. Use the .length property to check the length of the array. Lastly, return the
price variable:
productPrice(variations) {
let prices = [];
for(let variation of variations) {
if(!prices.includes(variation.price)) {
prices.push(variation.price);
}
}