Do not merge, insert Entities in Array

I am having an issue with calculating the total order prices (in USD) in an object array. Instead of summing the total, the order totals are being concatenated. How can I ensure that addition is performed instead of concatenation?

<body>
<p id=sales></p>
<script>
var sales, i, x = "";

sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]}

for (i in sales.orders) {
    x += sales.orders[i].total_price_usd + ', ';
}
var numbers = [x];
function getSum(total, num) {
    return parseFloat(total) + parseFloat(num);
}
document.getElementById('sales').innerHTML = '$' + numbers.reduce(getSum);
</script>
</body>

Answer №1

This code does not generate an array of numbers:

var numbers = [x];

Instead, it is creating an array with a single element that is a string, similar to this:

var numbers = ["92.05, 14.90, 17.90, 14.90"]

When you use numbers.reduce(), it only processes the first number in the string and does not iterate over all of them. Storing a string in a variable does not automatically parse it as JavaScript source code.

To correctly create an array of numbers, you should use this approach:

var numbers = []
for (var i = 0; i < sales.order.length; i++) {
    numbers.push(parseFloat(sales.order[i].total_price_usd));
}

Alternatively, you can perform the addition within the loop itself instead of using reduce() later on:

var total = 0;
for (var i = 0; i < sales.order.length; i++) {
    total += parseFloat(sales.order[i].total_price_usd);
}

Answer №2

To assist with the task at hand, consider utilizing parseFloat() on the variables and initializing x to 0.

var sales, i, x = 0;

sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]}

for (i in sales.orders) {
    x += parseFloat(sales.orders[i].total_price_usd);
}
var numbers = [x];
function getSum(total, num) {
    return parseFloat(total) + parseFloat(num);
}
document.getElementById('sales').innerHTML = '$' + numbers.reduce(getSum);
<div id="sales"></div>

It is important to note that when performing addition with floating point numbers in JavaScript, there may be slight discrepancies. Is floating point math broken?

Answer №3

  • To access the array sales.orders directly, you can use this method
  • In the function getSum, retrieve the price in USD using num.total_price_usd

var sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]};

//------------- Make sure to validate this logic
var i, x = ""

// Create an array like this: ["1, 2, 4, 5"].
for (i in sales.orders) {
    x += sales.orders[i].total_price_usd + ', ';
}
var numbers = [x];
//-------------------------------------------

function getSum(total, num) {
    return parseFloat(total) + parseFloat(num.total_price_usd);
}

document.getElementById('sales').innerHTML = '$' + sales.orders.reduce(getSum, 0);
<p id=sales></p>

Answer №4

To calculate the total, you can utilize the reduce method along with the Number constructor:

sales = {"orders": [{"total_price_usd": "92.05"}, {"total_price_usd": "14.90"}, {"total_price_usd": "17.90"}, {"total_price_usd": "14.90"}]}

const total = sales.orders.reduce(
  (sum, order) => sum + Number(order.total_price_usd), 
  0
)

console.log(total)

parseFloat and unary plus sign + are also alternatives for this calculation. Some find the use of Number more readable, but personal preferences may vary.

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

Uncertainty surrounding the handling of children/props rendering - at what point are expressions actually assessed?

I'm experiencing an issue with my progress bar component and its usage in another component: const Progress = ({children, show}) => { if (!show) return <ProgressBar />; return children; } const AnotherComponentUsingProgress = () => { ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Displaying an external webpage within a Backbone application

Is it feasible to display an external webpage in a view by using its URL? I am working with Backbone and Handlebars. var AuthorizeInstagramView = Backbone.View.extend({ template: Handlebars.compile(template), initialize: function () { }, ...

Exploring the Wonders of React Memo

I recently started delving into the world of React. One interesting observation I've made is that when interacting with componentized buttons, clicking on one button triggers a re-render of all button components, as well as the parent component. impo ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Using json_encode in PHP results in nullification of HTML strings

I am working with an array that includes a string containing HTML tags as one of its elements. As I loop through the array and output the field, I can see the string. $positions = $jobs_dbc->getData($sql); foreach($positions as $position) { ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

What is the best way to assign a percentage width based on a variable in jQuery?

Is there a way to assign a dynamic width value to an element? Here is the code I am using: $(".menu_list_item").css({ width: width + "%" }); Unfortunately, this doesn't appear to be functioning correctly. If anyo ...

What is a sophisticated method to hide an element from view?

My dilemma involves a dropdown menu and a list of elements that are initially set to hidden using CSS. When an item is selected from the dropdown, it becomes visible. However, I am struggling with finding a way to revert the previously selected element b ...

Troubleshooting a Non-Responsive React onClick Event in ES6

I am a beginner in React and have been searching on various platforms like StackOverflow and the internet, but I cannot figure out why onClick is not working in my case. When I click the button, absolutely nothing happens. I have tried everything from putt ...

Creating a tree structure using an array of objects

I am working with an array containing the following data: const data = [ { id: 1, type: 'type 1' }, { id: 2, type: 'type 2', subtype: 'subtype 2' }, { id: 3, type: 'type 2', subtype: 'subtype 3' }, ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

Unable to include the index parameter in the subsequent $http request

Here is a code snippet showcasing a $http request to retrieve quizzes and their respective results. The problem lies in the fact that 'i' is representing obtained values instead of index. $http.get(url).success(function(response) { $scope.qu ...

NextJs issue: Your `getStaticProps` function failed to return an object

I am currently developing a web application using NextJs. On one of the pages, I am trying to make an API call to fetch data and display it. However, during compilation, I encountered an error. The specific error message is: Error: Your `getStaticProps` f ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

How can I include a request header in a link using an EJS template in Express/Node.js?

I am currently attempting to create a route that can only be accessed if the user is authenticated with JWT using the middleware below. However, I'm facing an issue in passing the token in the GET request from the client side. It functions correctly o ...

Using JavaScript to Implement a Scrolling List

Currently, I am diving into the world of coding with HTML, JavaScript, and CSS for a college project. Unfortunately, my instructors aren't providing any assistance, so I'm turning to you for help. I have managed to put together some code to crea ...

What is the best way to assign a value to a class variable within a method by referencing the 'this' keyword?

Is there a way to set the state of this Ionic react app when displaying the outcome of a reset service? I am facing challenges with using this.setState({resetSuccess}) within a method due to scope issues. (Details provided in comments) Here is the relevan ...

The execution of Ajax is not taking place

Hey, I'm facing an issue with AJAX in my project. It's working fine in other files, but for this specific instance where I call scripts/claim.php and pass an id parameter via GET, it's not functioning as expected. HTML <input type="hidd ...

What is the process for invoking a JavaScript function from the code-behind of an Asp.Net application?

Here is a sample of my JavaScript function : function NeedToExport() { alert('Time to export your data!'); } Additionally, in my ASP.NET code behind : Page.ClientScript.RegisterStartupScript(this.GetType(), "ExportKey", "NeedToExport();"); ...