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

AgGrid supports multi-line content within its cells

I attempted to utilize this solution, however, it is not functioning properly for me. While it does resize the column height correctly, the text is still not wrapped as expected. Ag-Grid - Row with multiline text let gridOptions = { columnDefs: column ...

The argument type does not match the parameter type partial<>

While attempting to validate my Ionic React form, I encountered an error when calling the validationSchema within the useForm method. The specific error message received is as follows: Argument of type '{ validationSchema: ......' is not assignab ...

Cross-Origin Request Sharing (CORS) problem encountered while making an API call with

My current challenge involves calling an API that returns data in XML format as a response. While testing the .htm file on my local machine, I encountered the following error. https://i.stack.imgur.com/FsvZ0.png Similarly, running it from the codepen.io ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...

Cannot get the before-leave transition JavaScript hook to function properly in Vue.js

I am facing an issue with my variable, transitionName, in the beforeLeaveHook function. Despite attempting to change it to 'left', the value remains stuck at 'right'. Any assistance on resolving this matter would be greatly appreciated. ...

The delete button in the "Chip" component of React Material-UI is not functioning as expected

I'm having trouble with the "Chip" control and its "X" button functionality. Unlike the examples shown here: http://www.material-ui.com/#/components/chip Adding the "onRequestDelete" property does include the "X" button, but it doesn't respond t ...

Discovering the total number of tickets based on priority in an array with Javascript

I have the following data set { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"High", task_id:T1 }, { agent_id:001, priority:"Medium", task_id:T1 } { agent_id:002, priority:"High", task_id:T1 ...

"Utilizing Node.js to access modules with their absolute

My directory structure is as follows: -- app/ |- models/ |- user.js |- config.json I am trying to make my user.js file require the config.json. Currently, I am using require('/config') but it doesn't seem to be working. Can som ...

The issue persists with setState not functioning correctly and the checkboxes for filtering not registering as checked

I am currently in the process of developing a simple ecommerce platform which focuses on shoe shopping. Users will be able to search for shoes and apply filters based on brand and type. Here's where I stand with my progress: Clicking on filter check ...

Prevent opening links in new tabs or using control/middle click for specific links?

I'm looking for a way to prevent specific links from opening in a new tab when users attempt to do so (similar to how Gmail handles it). This will help prevent individuals from loading pages that are intended to be loaded through ajax on their own. ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

Retrieve the value of a JSON array containing only a single object using jQuery

In my project, I have a jQuery file and a PHP file. If the PHP file successfully completes the process, it returns the value 2 using `echo json_encode(2)`. I am able to catch this value in the jQuery file and display a string on an HTML div without any iss ...

Could someone assist me with understanding how to use the Load function in JQuery?

I have a set of links with the class "ajax" that are meant to fetch content from an element with the id "test" in the file "data.html" located in the same directory. This content should then be inserted into the div with the id "content" on my page: <s ...

Error message: Unable to access the state property of an undefined object

I've been attempting to integrate a react sticky header into my stepper component. However, I've encountered an issue where it doesn't render when added inside my App.js file. As a result, I've started debugging the code within App.js ...

Should we consider the implementation of private methods in Javascript to be beneficial?

During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option. Two alternatives were discussed: Using a constructor and prototype containing all functions, where non-API meth ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

Trapped in the clutches of the 'Access-Control-Allow-Origin' snag in our Node.js application

Our nodeJS application is deployed on AWS Lambda, and we are encountering an authentication issue with CORS policy when trying to make a request. The error in the console states: Access to XMLHttpRequest at 'https://vklut41ib9.execute-api.ap-south-1 ...

Manipulating CSS Class Properties Using JavaScript

In my JavaScript application, there is a functionality that loads a list of items for users to click and view detailed information in a separate div on the page. Users should be able to interact with and make modifications to these individual item overview ...

Combining PHP Variable with URL String

<td><input type="submit" onClick="window.location.href='https://www.'.$myValue.'.test.com'" value="Click!"></td> I am trying to create a button that will redirect to one of eight possible URLs based on a variable. How ...

Can you explain the significance of "javascript:void(0)"?

<a href="javascript:void(0)" id="loginlink">login</a> The usage of the href attribute with a value of "javascript:void(0)" is quite common, however, its exact meaning still eludes me. ...