Product Sums

I am facing a challenge with my array:

money(v, q)

[50, 2]
[20, 2]
[10, 2]
.
.
.
n

I have a specific calculation that I need to perform.

(money[0].v * money[0].q) + (money[1].v * money[1].q) + (money[n].v * money[n].q)

Can anyone provide assistance with this task?

I attempted to solve it using the following code snippet:

 for (i = 0; i > money.length; i++)
 {
 (money[i].v * money[i].q) + (money[i++].v * money[i++].q)
 }

However, I realized that there is a mathematical error in my approach and I am not sure how to correct it.

Your help would be greatly appreciated. Thank you.

Answer №1

It seems like the structure of your array is a bit unclear to me. Assuming it's an array of arrays similar to this example [ [50,2], [20,2], [10,2] ].

If my assumption is correct, you might want to consider utilizing the Array.prototype.reduce() method.

For more information, you can refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

const arrayOfArrays = [
  [50, 2],
  [20, 2],
  [10, 2]
];
const reduced = arrayOfArrays.reduce((a, c) => a + (c[0] * c[1]), 0);
console.log(`Total: ${reduced}`);

Answer №2

let total = 0
for (let j = 0; j < payment.length; j++){
 total += payment[j].v * payment[j].q
 }

To calculate the total sum, a variable is initialized before the for loop. During each iteration of the loop, the product of v and q corresponding to the current index value is added to the total.

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

Set a controller variable equal to a value assigned to a JavaScript variable within a view

As a newcomer to CodeIgniter and JavaScript, I am facing the challenge of assigning a value from a variable created in JavaScript in my view to a variable in my controller. Can someone guide me on how to achieve this? The main objective is to validate an ...

What is causing the 'info' object to be undefined?

transporter.sendMail(mailOptions,(error,info)=>{ if(error) console.log(error) console.log('Message Sent: '+info.messageId) console.log('Preview URL: '+nodemailer.getTestMessageUrl(info)) res.redirect('contacts', ...

Modify the name of the selected option value

I am working on an html code where I need to replace the values 0, 1, and 2 with USA, Australia, and Canada respectively. I also need to know the name of these values in my MySQL database. Thanks! HTML <form method="post" id="countriesForm" name="cou ...

Sorting numbers in JavaScript from highest to lowest

I have the following variables: let var1 = 20; let var2 = 10; let var3 = 40; let var4 = 9; let var5 = 6; let var6 = 51; I am looking for a way to sort these variables from highest to lowest, and return their names in the sorted ...

Having trouble with a jumpy carousel? After each transition, it seems like the image is hopping within the frame, getting smaller and then bigger

As I am still new to coding and using tools like bootstrap and Dreamweaver, I encountered an issue with a carousel on my website. Everything was working smoothly until the images started losing the bottom half when auto-scrolling or clicking to scroll righ ...

Exploring Keypress events with Dojo's 'on' module

Recently, I've started utilizing Dojo's latest on module for event handling. It has been working well so far, but a new issue has cropped up. Specifically, when using the keypress event, I am unable to retrieve the character value (such as "2" or ...

Ways to avoid duplicate entries in a database without the need to individually verify each value's

One way to prevent duplicate input data in a table is by running a simple query to check if the value already exists. SELECT `id` FROM TABLE WHERE `title` == 'test' It is important to note that PHP does not support multiple SQL requests in a si ...

Avoiding superfluous API calls with Redux thunk - how can you do it?

My action.js file contains the following code: import axios from 'axios'; export const SEARCH_TERM = 'SEARCH_TERM'; export const SAVE_SEARCH = 'SAVE_SEARCH'; export function search(query) { const githubApi = `https://api. ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...

Tips for concealing the scrollbar on Firefox while still allowing scrolling within a div container

Is there a way to hide the scrollbar in Mozilla Firefox without preventing scrolling within a specified div? I have tried using the following CSS, however, I do not want to include "overflow-x: hidden" in the div that already has a scrollbar. Additionally ...

Update the variable values in the Onclick function

I am trying to modify the onClick function attached to a button. My goal is to change the function var from 'create' to 'update' when the page loads and also through other functions. I attempted the code below but it did not work as exp ...

Creating a blueprint for my AJAX setup to effectively incorporate a callback function

I'm currently working with AJAX to fetch timezone information in a function, but I need it to return the result. I've come to realize that AJAX is asynchronous, so I require a callback function. Although I have seen examples, I am struggling to u ...

Flipping a binary array?

Is there a optimized method for inverting a binary array of any length? For example, changing all 1s to 0s and all 0s to 1s within the array. var arr1 = [ 0, 0, 1, 1, 1, 0, ..., 1 ]; ...

Tips for implementing ajax and codeigniter to load additional comments on a web page

Is it possible to customize Codeigniter's default pagination to achieve a "viewMore" link style when loading more records using AJAX? The challenge lies in creating a div that automatically expands to handle large numbers of records, such as 10,000 a ...

transform specific keys of a JSON Array into a new JSON Array

Below is a JSON array I currently have: [{ "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d2e14131e180f183d1c0d0f1411531f1407">[email protected]</a> ...

What could be causing the values I push into the array to show up as undefined?

My current project involves a personality quiz where I store answer values in an array to later analyze and determine the user's dominant personality trait. However, I am encountering an issue where the answer value of an option being pushed into the ...

Having trouble with Isotope masonry functionality

While experimenting with Isotope from , I tested the reLayout method using the provided example found at . I copied the css and js to my page () but encountered an issue where clicking on the first element caused all other elements to move to the first col ...

Animation effects compatible with iOS devices are professionally crafted using CSS

I just implemented a custom hamburger menu with animation using HTML, CSS, and JavaScript on my website. The animation works perfectly on Android devices but not on iOS. Any suggestions for fixing this issue? I attempted to add the Webkit prefix to each p ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

What methods can be used to obfuscate my JavaScript code within the developer console?

Currently looking for a method to hide my JavaScript code from being visible in the browser's developer console while maintaining its functionality. Alternatively, I would like to restrict it to run only on a particular website. Grateful for any insig ...