What is the best way to implement a dynamic for-loop?

I need to calculate the sum of multiple arrays.

For example, I have a 2D array with an initial length of 2, but the length will change dynamically. Each element must have a length of 3.

function addSum(){
    let length =3;
    //calculate sum of two arrays
    let arrayGroup = [[1,2,3],[1,2,3]]

    for(let i=0; i< length ;i++){
       for(let j=0; j< length ;j++){
           let sum = arrayGroup[0][i] +  arrayGroup[1][j]
           console.log(sum)
       }
    }
}


//result in console should look like:
//2 
//3
//4
//3
//4
//5
......and so on

Additional Info:
arrayGroup = [[1,2,3],[1,2,3]]
1 st sum= 1+1 
2 nd sum= 1+2
3 rd sum= 1+3
4 th sum= 2+1
5 th sum= 2+2
6 th sum= 2+3
7 th sum= 3+1
8 th sum= 3+2
9 th sum= 3+3
These are all the sums of a 2-element array

if arrayGroup is a 3-element array [[1,2,3],[1,2,3],[1,2,3]]
1 st sum= 1+1+1 // arrayGroup[0][0] + arrayGroup[1][0] + arrayGroup[2][0]
2 nd sum= 1+1+2
3 rd sum= 1+1+3
4 th sum= 1+2+1
5 th sum= 1+3+1
6 th sum= 2+1+1
7 th sum= 3+1+1
....and so on, until listing all combinations 

The code above demonstrates how I obtain results for two elements, however, when the number of elements in arrayGroup becomes N, I am looking for a way to get the results for N elements (i.e. arrayGroup = [[1,2,3],[1,2,3],.......,[1,2,3]] ).

Answer №1

the computation you are attempting is known as the cartesian product of arrays, which can be referred to as the cartesian product of sets in mathematics.

function findCartesianProduct(arr1, arr2) {
    const result = [];
    
    for(let x of arr1) {
        for (let y of arr2) {
            result.push(x + y);
        }
    }
    return result;
}



let array = [[1,2,3], [1,2,3], [1,2,3]];

let finalResult = [0];

for (let x of array) finalResult = findCartesianProduct(finalResult, x);

console.log(finalResult)

furthermore, we have the opportunity to condense and shorten the code using higher-order functions, but it's important to grasp the logic before diving into syntactical enhancements.

In essence, the cartesian product is akin to multiplying two sets together. The provided code computes the product for N lists by sequentially multiplying one list with the existing result.

for example, if you wanted to compute a product of 1, 6, and 5, you could do:

result = 1

for (let x in [1,6,5] ) result = result * x

Additionally, note that when the elements are consistently [1,2,3], there might be faster methods to compute the final output because there is a predictable pattern rather than calculating the cartesian product of random elements.

Answer №2

Here is a potential solution based on my understanding of your query.

function calculateSum(){
    
    //calculate the sum of two arrays
    let arrayGroup = [[1,2,3],[1,2,3],[1,2,3]]
    let length = arrayGroup.length
    
    for(let i=0; i< length ;i++){
      let arr1 = arrayGroup[i]
      let position = i+1;
      if(position < length){
       let arr2 = arrayGroup[position]
    
        arr2.forEach(a=>{
          arr1.forEach(n=>{
          console.log(a+n)
          })
         
      })    
      }
     
    }
}

calculateSum()

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

What is the best way to retrieve all collections and their respective documents in Firestore using cloud functions?

Seeking to retrieve an array structured as [1year, 1month, etc] with each containing arrays of documents. Currently encountering a challenge where the returned array is empty despite correct snapshot sizes. Unsure if issue lies with push() method implemen ...

Is there a way to remove array elements once in order to replace them with new ones using a for loop?

My objective is to achieve the following: Assign an array value (list) to another array (options). If the user input (searchVal) matches a value in the list, remove existing options and add this match. Subsequently continue adding any additional matches w ...

Dynamically updating fields in PHP using jQuery's passed variable

In my web application, I have a selection of locker numbers available in a dropdown list that is populated from MYSQL/PHP. My goal is to display each locker's combination and location when a user selects a locker number from the dropdown list on the s ...

Converting a cURL response string into a JSON array using PHP

I am currently utilizing Curl to make a request to a REST API. Below is my code: #Initializing Curl $ch = curl_init('https://192.168.0.1/api/invoke/LicenseRequest'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch ...

Vue.js is unable to dispatch an event to the $root element

I'm having trouble sending an event to the root component. I want to emit the event when the user presses enter, and have the root component receive it and execute a function that will add the message to an array. JavaScript: Vue.component('inp ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

Error occurred due to an unexpected end of JSON input following a pending promise

I am currently developing a data handler that requires downloading a file for parsing and processing within the handler. To handle this, I have implemented the file request within a promise and called it asynchronously from other methods. Including the h ...

Utilizing the datepicker options function within a different function

I'm working on a function that utilizes a promise to retrieve data from an asynchronous ajax call: $("#mySelect").on('change', function() { var mySelectValue = $('#mySelect').val(); var promise = getAvailableDates(mySe ...

When clicking on a link in React, initiate the download of a text file

Usually, I can use the following line to initiate the download of files: <a href={require("../path/to/file.pdf")} download="myFile">Download file</a> However, when dealing with plain text files like a .txt file, clicking on ...

How can one go about constructing abstract models using Prisma ORM?

Among my various prisma models, there are common fields such as audit fields like created_at and updated_at. model User { id Int @id @default(autoincrement()) created_at DateTime @default(now()) updated_at DateTime @updatedAt email ...

Bring in TypeScript property from an external scope into the current scope

I am encountering an issue with my TypeScript code. Inside the anonymous functions, I am unable to change the properties of the class because they are out of scope. Is there a way to pass them in so that they can be modified? class PositionCtrl { ...

Using a modal within a map function: Tips and tricks

I've been working on a Gallery application using React.JS and Reactstrap. The application uses the map() function to display each piece of art in a Card. Each card has a button that triggers a modal to show more data from the map function. However, I& ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

Looking for repeating values in inputs excluding this one

In the midst of a medium-sized project, an issue has arisen. I have condensed the core problem into this code snippet. Here's what the code does: $(".6").focusout(function(){ if( $(".6").filter(function(){ return this.value;}).not(this).length>0 ...

Steps to obtain the original video file from a Google Drive link for embedding on a website

I have a video stored on Google Drive with a link that is supposed to provide the raw video file. However, when I click on the link, I am directed to an image instead. https://drive.google.com/uc?id=xxx How can I obtain the correct playable link to use th ...

Differences Between APP_INITIALIZER and platformBrowserDynamic with provide

I've discovered two different approaches for delaying an Angular bootstrap until a Promise or Observable is resolved. One method involves using APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: (configService: ConfigurationService) => ( ...

Attention: certain content may have been removed due to HTML sanitation

Hi there, I'm currently working on incorporating a search bar into a modal window by embedding HTML within the modal body. Here's how I've written the code: onClick() { const dialogRef = this.modal.alert() .size('lg' ...

The server is throwing a 403 error when trying to submit an AJAX request

I am currently working on a project similar to jsfiddle and encountering an issue during development. Whenever I attempt to make an ajax request with the JS alert() function in a text box, the server is returning a 403 error. Can anyone provide assistance ...

Mastering the art of jQuery UI development, similar to the techniques

I'm currently working on creating an abstraction layer for jQuery UI that enables the definition of Widgets as Objects, similar to ExtJS. Here's how it works: var mydialog = new $.ui.dialog({ modal:true, renderTo:'body', title:'T ...

d3.json is unable to parse a value of 'Infinity

My goal is to retrieve data from an SQLite database and convert it into JSON format for use with d3.js in order to create a graph. I have successfully obtained this data in JSON format using the following URL: http://localhost:8085/SQLQuery/?date1=2019-03 ...