By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Restaurant Bill - JavaScript task

+1 vote

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.


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

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

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

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}”.

asked in JavaScript category by user golearnweb

1 Answer

+1 vote

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)
        .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']);


answered by user mitko