How come my variable is pointing to the global scope variable?

After many attempts, I finally wrote a function that aims to identify all feasible permutations from an array of numbers. Below is the code snippet.

var perm = [];
var usedchar = [];

function findPossiblePermutations(array) {

  for (var index = 0; index < array.length; index++) {
    var currentNum = array.splice(index,1)[0];
    usedchar.push(currentNum);

    if (usedchar.length == 3) {
      perm.push(usedchar);
    }

    findPossiblePermutations(array);
    usedchar.pop();
    array.splice(index,0,currentNum);
  }
}

findPossiblePermutations([1,2,3]);

console.log(perm); //-> [[],[],[],[],[],[]]

My anticipation was to retrieve:

[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

I am puzzled as to why my expected output is not being achieved. Could someone shed some light on this issue?

Answer №1

Your current issue stems from using the same array for both your algorithm's intermediate result and storage, leading to a mix-up of data. To resolve this, consider separating the two arrays or cloning the usedchar array before pushing it into perm array. Take a look at this example in Plunker for reference: http://plnkr.co/edit/HQ6q8fo8S0K21cISQKVt


var perm = [];
var usedchar = [];
var another = [];

function findAllPermutations(arr) {
  for (var i = 0; i < arr.length; i++) {
    var x = arr.splice(i,1)[0];
    usedchar.push(x);

    if (usedchar.length == 3) {
      perm.push(usedchar.slice());
    };

    findAllPermutations(arr);
    usedchar.pop();
    arr.splice(i,0,x);
  };
};

findAllPermutations([1,2,3]);
console.log(perm);

Answer №2

perm.push(usedchar.slice());

This code modification ensures that the usedchar array is cloned, preserving its state at that specific moment. Without this adjustment, there would be six references to usedchar, each being altered and emptied by various operations.

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

Aggregating JSON Array data with specified row limits

In my Oracle 19 database, I am dealing with a JSON aggregated array that I need to segment and repeat after a specific number of rows. Here is an example: [{"personId": "13274614","surname": "SMITH"},{"personId& ...

A helpful guide on resetting ReactJs to its default state when data is not found

Currently, I'm fetching data from my database, but just for the sake of this question, I have opted to manually create an example with fake data. I am in the process of creating a search bar for my users to navigate through all the data retrieved fro ...

The body-parser module in express 4.0 is currently not accessible for the route handler

I am attempting to send a PUT request via Google Postman in the following format: PUT /updateUser/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debcbcbc9eadadadf0bdb1b3">[email protected]</a> HTTP/1.1 Host: loca ...

The expression for AngularJS ng-switch-when

I am currently working on creating a tabbed menu using the ng-switch directive. Within my Ctrl (streams), I have set the tabs and am keeping track of the selected one as selection: app.controller("StreamCtrl", function($scope) { $scope.streams = [{ t ...

Error message encountered: 'GlobalStyles' is not a valid export from the module '@material-ui/system' (referenced as 'SystemGlobalStyles')

./node_modules/@material-ui/core/GlobalStyles/GlobalStyles.js Error encountered while trying to import: 'GlobalStyles' is not exported from '@material-ui/system' (imported as 'SystemGlobalStyles'). I am currently grappling wi ...

Is it possible to use JavaScript for detecting third-party videos?

I'm currently developing an HTML5 video player that also has a fallback to flash. One of the challenges I am facing is that the video content is being provided by various third-party sources. It seems that some of these third parties serve videos bas ...

Utilize string paths for images instead of requires when resolving img src and background-image URLs

I have successfully implemented image loading with webpack using the file loader, but only when I require or import images. I am curious about how create-react-app achieves the functionality where everything in the public folder is accessible, for example, ...

Converting Date Formats in ReactJS: A Guide for Manipulating Date Formats within an Array of Objects

I am working on a React application using Next.js, and I need to convert the date format within an array of objects using the moment library. The data structure looks like this: [ { "date": "2020-12-22T00:00:00.000Z", & ...

What steps do I need to take in order to make fullscreen slides?

Seeking assistance in developing full-screen slides similar to those found on the following website... The browser scrollbar should be hidden, and the slides should automatically transition when scrolling up/down or using the up/down arrow keys, with the a ...

JavaScript Scroller that keeps on scrolling

Unique Continuous JavaScript Scroller I am currently working on a JavaScript scroller script that enables left to right and right to left scrolling on the click of next and previous buttons. The script is designed to work with 1 to 3 div elements in a con ...

Guide to increasing a field value in Backendless.com

Below is an overview of the table structure I have: Table data ---------------------------------- - User - ---------------------------------- | objectId | name | password | ---------------------------------- | z12ttttt | ...

Why does a Vue component throw errors prior to being rendered?

In the Home view, there are two components: Filter and Results. The Results component relies heavily on data from the vuex store, which is influenced by the Filter component. Once the filters are applied and the user interacts with Filter, the necessary da ...

Is it considered poor design to pass a function two levels deep? Are there other possible alternatives to achieve the same outcome?

I am currently working on a scenario involving componentA, which also contains another componentB with buttons that need to update the scene. My initial thought was to pass a function from the scene to componentB through componentA, but since I am new to ...

The button will be disabled if any cells in the schedule are left unchecked

I am seeking help on how to dynamically disable the save button when all checkboxes are unchecked. Additionally, I need assistance with enabling the save button if at least one hour is selected in the schedule. Below is my code snippet for reference: htt ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

When a link is clicked, submit a form and send it to several email addresses simultaneously

My form has been styled using the uniform jQuery plugin. Instead of using an input type submit for submitting the form, I have utilized a link and added some effects to it to prevent it from being formatted with uniform. <form> <ul> ...

Need help inserting an image into the div when the ngif condition is true, and when the ngif condition is false

Essentially, I have a situation where I am using an *ngIf condition on a div that also contains an image. This is for a login page where I need to display different versions based on the type of user. However, I'm facing an issue where the image does ...

Cut the string at "_B"

For some reason, this line of code is not functioning properly and I am unsure as to why: String[] stringHolder = string.split("_(B"); An error stating "Unclosed group near index 3" appears when I try to run the above code. In contrast, this line of ...

Increase the object name in localStorage to save information entered in input fields

For testing purposes only - do not use for production. I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted. However, I am encounte ...

Using JQuery to obtain an array of the widths of the td elements in a specific row

I am attempting to retrieve an array containing the width of all td's in a row. To start, I fetch the array of all the td's: datas = $('.totals').prev().find("tr").last().find("td"); Next, in order to confirm that I am using the $.map ...