How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which will be added to their wallet.

I attempted to solve this using multiple loops to iterate through each array and compare values, but I require a solution with algorithmic complexity On.

    var product = [
    {'name':'cookie', 'price':10},
    {'name':'coffee', 'price':2},
    {'name':'ice cream', 'price':4},
    {'name':'pasta', 'price':5},
    {'name':'peach', 'price':6},
    {'name':'pineapple', 'price':15},
]
var purse = [
    {'name':'Katya', 'cash':100},
    {'name':'Danya', 'cash':200},
    {'name':'Vanya', 'cash':400},
    {'name':'Sanya', 'cash':500},
    {'name':'Manya', 'cash':600},
    {'name':'Kira', 'cash':150},
]

var purchases = [
    {'name':'Katya', 'item':'cookie'},
    {'name':'Danya', 'item':'pasta'},
    {'name':'Danya', 'item':'coffee'},
    {'name':'Danya', 'item':'coffee'},
    {'name':'Manya', 'item':'pineapple'},
    {'name':'Katya', 'item':'ice cream','credit': 20},
]

Answer №1

Perhaps we could try a different approach. Instead of consolidating all the information into one set of objects, I opted to re-fetch the data on each loop iteration. This decision should make formatting easier. Hopefully, this solution serves as a good foundation for your needs!

var product = [
    {'name':'cookie', 'price':10},
    {'name':'coffee', 'price':2},
    {'name':'ice cream', 'price':4},
    {'name':'pasta', 'price':5},
    {'name':'peach', 'price':6},
    {'name':'pineapple', 'price':15},
];
var purse = [
    {'name':'Kate', 'cash':100},
    {'name':'Danny', 'cash':200},
    {'name':'Vanya', 'cash':400},
    {'name':'Sanya', 'cash':500},
    {'name':'Manya', 'cash':600},
    {'name':'Kira', 'cash':150},
];
var purchases = [
    {'name':'Kate', 'item':'cookie'},
    {'name':'Danny', 'item':'pasta'},
    {'name':'Danny', 'item':'coffee'},
    {'name':'Danny', 'item':'coffee'},
    {'name':'Manya', 'item':'pineapple'},
    {'name':'Kate', 'item':'ice cream','credit': 20},
];

function displayInfo(name, walletVal) {
  const displayArea = document.querySelector("#display");
  const spendSummary = document.createElement("div");
  spendSummary.classList.add("spendSummary");
  const nameEle = document.createElement("div");
  nameEle.classList.add("name");
  nameEle.innerText = name;
  spendSummary.appendChild(nameEle);
  const walletEle = document.createElement("div");
  walletEle.classList.add("wallet");
  walletEle.innerText = walletVal;
  spendSummary.appendChild(walletEle);
  displayArea.appendChild(spendSummary);
}

const names = [...new Set(purchases.map(e => e.name))];
for (const name of names) {
  const filteredPurchases = purchases.filter(e => e.name == name);
  const costs = filteredPurchases.map(
    ({item: itemName}) =>
    product.find(item => item.name == itemName).price
  );
  const creditsArr = filteredPurchases.filter(e => e.credit)
    .map(e => e.credit);
  const totalCredit = creditsArr.reduce((a,b) => a + b, 0);
  const totalCost = costs.reduce((a,b) => a + b, 0);
  const cash = purse.find(e => e.name == name).cash;
  const currentWallet = cash + totalCredit - totalCost;
  displayInfo(name, currentWallet);
}
#display {
  display: flex;
  justify-content: space-around;
  
  font-family: arial;
}

.spendSummary {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.name {
  box-shadow: 0 2px 2px -2px black;
}
<div id="display">
</div>

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

Handling events for components that receive props from various components in a list

In my code, I have a component called PrivateReview which includes event handlers for updating its content. export default function PrivateReview(props) { const classes = useStyles(); const removeReviewAndReload = async () => { await ...

Encountering an error while trying to run a Next.js application on Linux Mint

View the error screenshot After creating a new Next.js app with npx create-next-app, I ran npm run dev and encountered the following error message ...

Displaying random divs and subsequently animating them downwards using JavaScript

I am in the process of creating a random appearing div that then falls down. Here is the code I have so far: $(document).ready(function(){ $('#test').animate({top: 80 + '%'},900); }); <div id="test" style="background:#98bf21;heigh ...

Error Message for Sequelize Validation Fails to Appear as Expected

I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed: Oops! An error occurred. "Title" is required. "Author" is required. The issue I&ap ...

Display one of two divs after clicking a button depending on the input from a form field

My apologies for my limited knowledge in JavaScript and jQuery. I'm attempting to show one of two divs based on input from a form. Specifically, there's a button next to a form field that asks users to enter their zip code to check if they are wi ...

Leverage a single JavaScript file across all Vue components without the need for individual imports

My project includes a JavaScript file called Constant.js that stores all API names. //Constant.js export default { api1: 'api1', api2: 'api2', ... ... ... } Is there a way to utilize this file without having to impo ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

Utilize PHP to extract JSON data from the db-ip.com API

I am encountering an issue with the db-ip.com API that is supposed to display information about visitor IP addresses. However, my current script only outputs < pre > tags without anything in between. I would like all parameters from the API to be dec ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

What is the best way to utilize jquery's $.ajax function in conjunction with json and php to upload a file?

Can someone assist me with uploading a file using jQuery's $.ajax function? I am not getting any output and I'm unsure if my script is correct. Here is the code: $.ajax({ url:'newsup.php', data: "", type: 'POST', cont ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

Troubleshooting Vue.js 2: Difficulty with Vue locating files stored in the /assets directory (v-for loop)

My Vue-cli 3 project with Webpack has the following folder structure: /public /src /assets p1.jpg p2.jpg App.vue main.js I have read that in order for Webpack to recognize the /assets directory, require() should be used in JavaScript files ...

Using Javascript to generate a button that randomly chooses links within the webpage

Looking for help with JavaScript to select a link when a button is clicked on the page? Check out my code and let me know what I'm doing wrong. For the full code, visit: here HTML <!doctype html> <html lang="it" xmlns="http:/ ...

Ways to iterate through a JSON object within an array to extract specific data field

Currently, I am in the process of retrieving data from an API using PHP's curl function. The data structure returned by the API is depicted below: {"COLUMNS":["COCD","CONAME","KINDOFACCOUNT","ACCOUNTCODE","ACCOUNTNAME","TELNO", ... [truncated for br ...

Listening for select elements that have remained unchanged

My current situation involves a select box with predetermined options. One of these options is preselected when the page loads: <select name="select" class="js-choice-select"> <option value="option-1">Option 1</option> <option ...

Retrieve the keys stored within a complex array of objects

I am searching for a function that can transform my data, specifically an array of objects with nested objects. The function should only include keys with immediate string/number/boolean values and exclude keys with object/array values. For example: [ { ...

Issue with React component not displaying in the browser.Here are some

I am currently following a React tutorial on and I'm facing an issue where the Counter component is not displaying on the page. The generated HTML looks like this: <html> <head> <script src="/bundle.js" ></script> </he ...

What's the best way to trigger an alert popup after calling another function?

Here are some HTML codes I've been working with: <button id="hide" onclick="hide()">Hide</button> <p id="pb">This paragraph has minimal content.</p> My goal is to have the paragraph hide first when the button is clicked, foll ...

Setting the property of an object member using an array member within a JavaScript singleton

My JavaScript code includes a "singleton" class like this: ExpressionValidator = { // A map of function names to the enumerated values that can be passed to it. functionParamValues: { "Func1": ["value1", "value2", "value3"], "F ...