How is it possible for this variable to be altered without any modifications made to it in the current function?

This particular function receives two arrays as input: arrOne, which is an array comprising arrays of numbers, and arrTwo, which is an array containing numbers. My goal here is to generate every possible combination, followed by obtaining the unique combinations. However, I've encountered a stumbling block.

function multOrdProduct(arrOne,arrTwo){
  let backSet = [];
  let count = 0;
  let tempArr = new Array(arrOne.length);
  let permArrOne = [];
  let permArrTwo = [];
  let pushed;
  let setPart = [];
  
  for(i=0; i < arrOne.length; i++){
    permArrOne.push(arrOne[i]);
  }
// ^sets permArrOne to equal the same array as ArrOne
  
  for(i = 0; i < arrOne.length;i++){
    for(j = 0; j < arrTwo.length; j++){

      setPart = permArrOne[i];
      
      console.log(permArrOne[i]);
      
      setPart.push(arrTwo[j]);
      backSet.push(setPart);
    }
  }
  return backSet;
}

I initially believed that permArrOne[i] would remain unchanged since no value assignment is made to it. Can anyone explain why it changes in each iteration?

Answer №1

When you reference permArrOne in setPart without cloning it, any changes made to setPart will also affect permArrOne.

.slice() is a method that can be used to create a new array:

function multiplyArrays(arr1,arr2){
  let backSet = [];
  let count = 0;
  let tempArr = new Array(arr1.length);
  let permArr1 = [];
  let permArr2 = [];
  let pushed;
  let setPart = [];
  
  for(i=0; i < arr1.length; i++){
    permArr1.push(arr1[i]);
  }
// ^sets permArr1 to be the same as arr1
  
  for(i = 0; i < arr1.length;i++){
    for(j = 0; j < arr2.length; j++){

      setPart = permArr1[i].slice();
      
      console.log(permArr1[i]);
      
      setPart.push(arr2[j]);
      backSet.push(setPart);
    }
  }
  return backSet;
}

let array1 = [[0, 1], [1, 2]]

let array2 = [0, 1, 2]

multiplyArrays(array1, array2)

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

VueJS is unable to identify the variable enclosed within the curly braces

I recently started learning VueJS and I've hit a roadblock. My goal is to display a variable, but for some reason, instead of seeing the product name, all I get is {{product}} Here's the HTML code I'm using: <!DOCTYPE html> <html l ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

The ImportJSON function in Google Sheets is failing to return results when using a path with an

I am utilizing ImportJSON (https://github.com/bradjasper/ImportJSON) for the purpose of creating a spreadsheet and importing JSON data. /* * The provided JSON feed is flattened to create a two-dimensional array while importing it into a Google Spre ...

Grab a hold of the currently active controller in Angular

Is it possible to access a reference to the current instance of the controller from within its definition? My goal is to use `$compile` to create a modal and have it bound to the same controller that initiated its creation. Below is an example of what I w ...

Exploring the integration of Formik with Material-UI's select field - A step-by

Trying to implement Formik with Material-UI's Textfield component using the select attribute. Every time I change the option, it shows this warning: Material-UI: You have provided an out-of-range value null for the select (name="subIndicatorId& ...

Step-by-step guide on redirecting to a different page following a successful POST API call using Jquery

I have the code below in my JavaScript file. $scope.addLookupAction = function () { $("#importForm").attr("action", 'xyz.com'); success:function(response) { $log.info("Redirecting to lookup home page"); ...

Suggestions for resolving the issue of my header being truncated on mobile browsers?

I am facing an issue with my header and need assistance in fixing it. The problem occurs when scrolling down, as it cuts off a part of the header, but returns to normal when scrolling back up. I suspect the hamburger menu might be causing this issue becaus ...

Different options for reading large files during an AJAX file upload

It seems that php's file_get_contents is not able to handle large files. What can be done as an alternative if it is causing a "stack overflow" issue? HTML File <form id='test'> <input type='file' name='Receipt&ap ...

Using JavaScript to assign the title property to an <a> tag

I'm currently working on modifying a code snippet that utilizes jQuery to display the "title" attribute in an HTML element using JavaScript: <a id="photo" href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><i ...

Using jquery to remove textbox value when checkbox is unchecked

I have a single datatable created using jQuery. The first column of the table consists of checkboxes, and the last column contains textboxes. Because these elements are generated dynamically, they end up having identical IDs and names as shown below: $ ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

The functions .ajaxStart and .ajaxStop seem to be malfunctioning

Having trouble displaying and hiding a loading gif before and after an Ajax request using ajaxStart and ajaxStop. Here's what I have: HTML: <div id="loading" style="display: none"><img src="loading.gif></div> JS: $("#searchForm") ...

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

Unforeseen anomalies arise when deleting an element from an array in a React application

I've been scouring for a solution, but I could really use some human guidance. I have a basic form where users can input additional fields. They also have the option to delete irrelevant fields. The problem arises when trying to remove these fields. ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

Exploring First-Person Shooter Rotation with THREE.JS

I recently attempted to create a rotation system for a First Person Shooter game using THREE.JS. However, I encountered a strange issue where the camera would pause momentarily before returning, especially at certain rotations. When checking the rotation ...

Java's tostring() function is showing unusual values

My attempt to create a string reversal algorithm involved using two pointers, one at each end of the string. One pointer (i) points to the beginning while the other pointer (j) points to the end. The elements located at these positions are swapped and then ...

Ways to trigger Bootstrap modal through a PHP GET call

I have been searching for a solution to create a modal similar to this one, but I haven't found anything yet. My requirement is that when we pass true in a GET request, the modal should be displayed. Otherwise, if there is no value specified in the $ ...

The precision of the css function in jQuery

Possible Duplicate: jQuery and setting margin using jQuery In the HTML snippet below, I have set margins for a paragraph element to center it: <p style="margin-left:auto; margin-right:auto; width:200px;">Hello</p> After that, I attempted ...

The i18n feature in node.js seems to be malfunctioning as the setLocale function is not working properly. Regardless

Something seems off with my usage of the i18n library, but I believe I'm following the correct steps. I've been attempting to switch the locale. Here's my current code. Despite calling setLocale on the global i81n variable, it continues to ...