A technique for combining the elements of one array in a loop and then transferring them to another array before adding them to an object

In order to streamline the process of calculating tip percentages based on bill amounts, I have developed a method within the object itself. However, to prevent redundancy, I have also created a separate function called calculateTip and a dedicated for loop to iterate over the bills stored in the John object.

After successfully computing individual tips and storing them in the tips array, my next goal is to add each original bill amount to its corresponding tip and push the result to the finalBills array.

This means that the finalBills array should display the total sums for each set of bills and their respective tips: [142.6, 57.60, etc...]

Here is what I have accomplished so far:

var john = {
    patron: 'John',
    bills: [
        124,
        48,
        180,
        268,
        42
    ],
    tips: [],
    finalBills: []
}

function calculateTip(bill) {
    if (bill < 50) {
        percentage = (20 / 100);
    } else if (bill >= 50 && bill < 200) {
        percentage = (15 / 100);
    } else {
        percentage = (10 / 100);
    }
    return percentage * bill;
};

// console.log(john.bills.length);

for (var i = 0; i < john.bills.length; i++) {
    var bill = john.bills[i];
    console.log(bill);

    var tips = calculateTip(bill);
    var roundedTips = tips.toFixed(2);
    john.tips.push(roundedTips);
    console.log('These are the tip amounts: ', roundedTips)

    var finalBill = (roundedTips + bill);
    console.log('Final amounts: ', finalBill)
};

console.log(john)

Answer №1

Utilizing the toFixed method results in a string output rather than a numeric one. Consider employing parseFloat. If you wish to include the method within an object, you can implement it using a class:

class Customer {
  constructor(customer, bills) {
    this.customer = customer;
    this.bills = bills;
    this.tips = [];
    this.finalBills = [];
  }

  calculateTip(bill) {
    let percentage;
    if (bill < 50) {
      percentage = (20 / 100);
    } else if (bill >= 50 && bill < 200) {
      percentage = (15 / 100);
    } else {
      percentage = (10 / 100);
    }
    return percentage * bill;
  }

  calculateFinalBill() {
    for (var i = 0; i < this.bills.length; i++) {
      var bill = this.bills[i];
      //console.log(bill);
      var tip = this.calculateTip(bill);
      var roundedTips = parseFloat(tip.toFixed(2));
      this.tips.push(roundedTips);
      //console.log('These are the tip amounts: ', roundedTips);

      var finalBill = (roundedTips + bill);
      //console.log('Final amounts: ', finalBill);
      this.finalBills.push(finalBill);
    }
  }
}

const john = new Customer('john', [124, 48, 180, 268, 42]);
john.calculateFinalBill();
console.log(john.finalBills);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble receiving the response calculation from the express server?

Can you please help me identify what is missing in my code? This is the HTML code I have so far: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Calculat ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

Implementing SweetAlert2 in Vue.js to create a modal prompt for confirmation prior to deleting an item

I'm encountering an issue with sweetalert2 while using Laravel Vue for my app development. My goal is to have a confirmation modal pop-up when deleting a row from the database. However, whenever I click "Yes", the item is successfully removed. But if ...

ag-Grid incorporating new style elements

For my Angular application, I have a simple requirement of adding a CSS class when a row expands or collapses to highlight the row. I attempted to use gridOptions.getRowClass following the documentation at https://www.ag-grid.com/javascript-grid-row-styles ...

Utilize Redux Toolkit to efficiently share actions across different slices of state

How can I efficiently share common actions across multiple redux state slices? For instance, let's say I have an updateField action that I want to use in various slices other than just the profile slice. Should I import it from an external file for r ...

Generating a port file upon starting the Express server

I have encountered a problem while using the node v20.12.2 version in my application and starting the express server. Every time I start the server, it creates a file with port 5004; in my project folder. Subsequently, when I attempt to restart the server, ...

Enable automatic dropdown menu activation on mobile browsers specifically tailored for Android devices

Is there a way to automatically trigger the opening of a combobox on Android device browsers? Here is the code I have: <!doctype html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> ...

The video element in HTML5 is not showing up on Safari browsers, but it is functioning properly on Chrome

I have set up a video slider on my webpage. You can view the site The code is functioning perfectly on Chrome and iOS Safari, but there seems to be an issue on desktop browsers. When inspecting the page in Safari, the video elements are present in the HTM ...

What is the best way to find a specific value in a NumPy array?

In my work within the image processing field, I have successfully converted an image into a matrix. This matrix contains only two values: 0 and 255. Now, I am seeking assistance in identifying the columns and rows where the value 0 is repeated within thi ...

Incorporating information from an array into a Chart.js line chart

How can I dynamically add data in a loop for different array sizes using the code provided below? The data stored in dataGraph and measureAttr holds the attributes needed. currentChart = new Chart(document.getElementById("chart"), { type: &apo ...

Modify the conditions of a CSS file in Bootstrap using JavaScript

My project requires internationalization support for right-to-left languages like Arabic and Hebrew, so I need to modify some Bootstrap classes (such as col) to float right instead of left. I am using create-react-app with babel/webpack and react-bootstra ...

Managing numerous hub connections from a JavaScript client with SignalR

Is it possible to manage multiple active connections to various hubs using a single JavaScript SignalR client? UPDATE What I actually meant was the capability to connect to different URLs (where one can modify the connection URL through $.connection.hub.u ...

AngularJS directive for Ionic Leaflet - Utilizing Service to switch tileLayer from side menu

I am currently experimenting with developing an ionic app for the leaflet-angularjs-directive. Unfortunately, there are not many demos available for me to test out. The specific demo I am using is called ionic-leafletjs-map-demo by calendee on GitHub whic ...

Is it possible in Javascript to verify if a different script has been triggered?

I recently created a pop-out menu for a website using HTML and Javascript. The menu currently has a button that opens a div container with a close button inside it. While the buttons are functioning properly in hiding the div, the elements within the div d ...

Exploring deeply nested objects in Reactjs?

As a newcomer to Reactjs, I find myself working with an object structured like the example below. In my functional component, I am aiming to iterate through the keys at the top level of this object hierarchy (namely A, B, C) and display the value associate ...

The XML data is valid, however the responseXML property in the XMLHttpRequest response is null

Click here to access the API URL, which returns XML data. However, the responseXML property in the XMLHttpRequest response is coming back empty. How can I retrieve the XML data from the response? document.body.onload = loadXMLDoc(); function loadXMLDoc ...

Add characterizations to object utilizing cropper plugin

After obtaining image attributes from the cropper plugin, I am looking to include two additional values: var data = $img.cropper('getData'); //Object {x: 90, y: 60, width: 720, height: 480, rotate: 0…} image_identifier = $('.image_identi ...

Retrieving URL parameters and excluding a particular parameter from the list

I am looking to extract a specific parameter from the URL. Here is my scenario: Initially, the page loads with a URL like this: Upon loading the page, a function is triggered to add an entry to the history using pushState, resulting in a new URL such as ...

Interacting with jQuery mouse events on elements below the dragged image

I'm attempting to create a drag-and-drop feature for images using jQuery. While dragging, I generate a thumbnail image that follows the mouse cursor. However, this is causing issues with detecting mouseenter and mouseleave events on the drop target pa ...

Retrieve the value of a specific key from the previous state object using the useState hook

I've searched exhaustively on stack overflow, but couldn't find a similar solution. I need to update an object key-value pair without using the old value. Let's consider a graph declared using useState: const [graphBounds, setGraphBounds] ...