What is causing the issue with the "r" array not functioning correctly within the loop?

Why is the array not pushing correctly into r during the loop?

If I change

if((pivot + originArr[c]) <= 5)
to
if((pivot + originArr[c]) <= 3)

My result is incorrect:

[ [ 0, 1, 2, 3, 4 ],
  [ 0, 1, 2, 3, 4 ],
  [ 0, 1, 2, 3, 4 ],
  [ 0, 2, 3 ],
  [ 1, 2, 3 ] ]

The expected result should be

[ [ 0, 1, 2], [ 0, 1, 3], [ 0, 1, 4], [ 0, 2, 3 ] ]

If r is not empty, it will recursively send the first iteration result back to the function for computation until "r" is empty. Instead of pushing individual arrays to "r" for every c loop.

var data = [0, 1, 2, 3, 4, 5];

function compute(originArr, filterArr) {
  var r = [];
  var arr;

  let firstLoop = false;
  if (filterArr.length == 0) {
    firstLoop = true;
    arr = originArr;
  } else {
    arr = filterArr;
  }

  arr.forEach(function(i, index) {
    
    var pivot;
    if (firstLoop) {
      pivot = index;
    } else {
      pivot = parseInt(i.slice(-1));
    }
    var nextIndex = pivot + 1;
    console.log(pivot, nextIndex);
    for (var c = nextIndex; c < originArr.length; c++) {
      let tempResult = [];
      console.log(c);
      if (pivot + originArr[c] <= 3) {
        if (firstLoop) {
          tempResult.push(index);
        } else {
          tempResult = i;
        }
        tempResult.push(c);
        console.log(tempResult);
        r.push(tempResult); // suppose to push [0,1], [0,2], [0,3], [1,2] for the first iteration
      }
    }
  });

  if (r.length > 0) {
    return compute(originArr, r);
  } else {
    return arr;
  }
}

console.log(compute(data, []));
//Final result should be [[0,1,2]]

Answer №1

It seems I have identified the issue.

The problem lies in how we are trying to duplicate the array.

tempResult = i;

This method will alter the reference to 'i' once the new number is added to tempResult.

My proposed solution is to change the way we duplicate the array to:

tempResult = [...i];

This approach to cloning will not impact the original reference.

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

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

Implementing Angular CDK for a dynamic drag-and-drop list featuring both parent and child elements

I'm currently working on setting up a drag and drop list within Angular using the Angular CDK library. My goal is to create a list that includes both parent and child elements, with the ability to drag and drop both parent items as well as their respe ...

How can I integrate the native calendar of an Android device in Phonegap?

What is the best way to add an event to an Android device's calendar using phonegap? I need to make sure it works on Android Version 2.3 and above. The available plugins are not functioning correctly, so I am looking for alternative solutions. ...

JavaScript JSON request denied

As I develop a website, I am encountering an issue with my query requests from local host. Whenever I try to query from Google or the specific address provided, I do not receive any results. Is it possible that there are query limits set for certain URLs ...

"Enhance your data management with a dynamic React JS table

While attempting to modify the table from the react js docs linked here, I encountered some unexpected issues as shown in the screenshots below. https://i.sstatic.net/u2ck6.png We are trying to filter based on "lBird" https://i.sstatic.net/vCta4.png Th ...

Using the LIKE operator in MSSQL within a Node.js SQL query

Is there a way to fetch data even when the query value for "naziv" is not an exact match with the value in the table, but just similar? const sqlConfig = require("../config/ms.config") exports.data = async (req, res) => { const { sifar ...

Updating an element in the array stored in localStorage using Angular 6

Need to update a specific property of an object stored in local storage, here is a sample object structure: appID: {"userid":0,"username":null,"password":null,"saltPassword":null,"kraPassword":null,"kraPasskey":null,"panNumber":"BTRGH8774L","dob":"20/05/1 ...

A recursive function enhanced with a timeout mechanism to avoid exceeding the stack call limit

Trying to search for images on any object of various depths using a recursive function can lead to a Maximum call stack size exceeded error in certain cases. A suggested solution here involves wrapping the recursive function in a setTimeout, but this seems ...

Include the model.obj file into the three.MESH framework

I am a beginner in three.js and I am developing an augmented reality application on the web to showcase plates of food. Currently, I have successfully displayed a cube. However, when I attempted to display a model.obj instead of using geometry and material ...

Organizing Data to Create a D3 Tree Layout from a CSV

My CSV file has the following structure source, target, name, value1 , percentange A1 A1 T1 200 3% A1 A2 T2 340 4% A1 A3 T3 400 2% I want to create a tree diagram similar to this D3 Pedigr ...

Strategies for capturing a 404 error in an Express router

Trying to capture the 404 page not found error in an express router. Using a simple example : const express = require('express'); const app = express(); const router = express.Router(); // ROUTER MID BEFORE router.use((req, res, next) => { ...

Use the ng-pattern regex to specifically identify instances where a pattern occurs only once

Looking for a string pattern 'abcd' followed by a colon(:) and any number of integers, with the restriction that this pattern cannot be repeated. Here are some examples of valid patterns: - abcd:23415 - abcd:23 And invalid patterns: - asda:4 ...

Securing JWT signatures for both server-side and client-side environments

I am looking to authenticate Salesforce's OAuth 2.0 JWT Bearer Flow using both node.js and a Browser. I have generated a public key and a private key on Windows by running the following command. openssl req -x509 -sha256 -nodes -days 36500 -newkey r ...

Is it possible to incorporate a selection box along with the Raycaster in Three.js?

In my GLTF scene, I have been exploring the use of the example selection box (code) to select multiple meshes. Unfortunately, the current approach is providing inaccurate results as it selects based on the centroid of each mesh and includes meshes that ar ...

Prevent the opening of tabs in selenium using Node.js

Currently, I am using the selenium webdriver for node.js and loading an extension. The loading of the extension goes smoothly; however, when I run my project, it directs to the desired page but immediately the extension opens a new tab with a message (Than ...

Printing an array of characters in a simple dungeon crawler game

Hello, I am facing a challenge with my C++ programming project where I am trying to create a simple "dungeon crawler". The issue I encountered is that when the player moves left or right in certain spaces, another player character appears on the screen, r ...

Is it possible to verify the value of the onclick attribute using jQuery?

Currently, I am facing a challenge with my ajax / php pagination system. I am struggling to apply the active class to the correct link in order to style it as selected. My question is, can I retrieve the value of onclick="" using jquery? Here is an examp ...

Exploring the world of JMeter: capturing sessions with JavaScript and jQuery

I need to capture a user session in order to conduct a performance test. I have been using the JMeter HTTP(S) Test Script Recorder, but unfortunately it is not recognizing javascript and jquery. The error message I'm receiving is: JQuery is not def ...

It is not possible to store data in instances of the same class if they are declared as an array

Recently, I delved into the world of learning java and faced an interesting requirement. My goal is to create instances of my own class in the form of an array. Subsequently, I aim to reference each object using a loop and input data accordingly. The class ...

What is the significance of declaring a variable outside of a JavaScript function? (Regarding jQuery and #anchor)

In my jQuery function, I needed to determine the current #anchor of the page. To achieve this, I utilized the jQuery URL Parser plugin. $.fn.vtabs = function() { alert("The current anchor is "+$.url.attr('anchor')); } Initially, the code c ...