[Risolto] Restaurant Bill - JavaScript task

  

3
Argomento iniziale

You are tasked to write a javascript function that receives an array of purchases and their prices and prints all your purchases and their total sum.

The input comes as an array of string elements – the elements on even indexes (0, 2, 4…) are the product names, while the elements on odd indexes (1, 3, 5…) are the corresponding prices.

Examples:

Input:
['Beer Zagorka', '2.65', 'Tripe soup', '7.80','Lasagna', '5.69']

Output:
You purchased Beer Zagorka, Tripe soup, Lasagna for a total sum of 16.14


Input:
['Cola', '1.35', 'Pancakes', '2.88']

Output:
You purchased Cola, Pancakes for a total sum of 4.23

The output should be printed on the console - a single sentence containing all products and their total sum in the format “You purchased {all products separated by comma + space} for a total sum of {total sum of products}”.

1 risposta
2

Here is the answer to this javascript task:

function restaurantBill(bill) {
    //let items = bill.filter(x=>!Number(x));
    let items = bill.filter((x, i)=>i % 2 == 0);
    //let sum = bill.filter(x=>Number(x))
    let sum = bill.filter((x, i)=>i % 2 != 0)
        .map(Number)
        .reduce((a, b)=>a + b);
    console.log(`You purchased ${items.join(", ")} for a total sum of ${sum}`);
}
 
restaurantBill(['Beer Zagorka', '2.65', 'Tripe soup', '7.80', 'Lasagna', '5.69']);
Condividi: