Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
Confused about pushing array into array, JavaScript

My code looks like this

var res = [];
var temp = [];

function Permutations(target, size) {
  if (size === 0) {
    res.push(temp);
    console.log(res);
    return;
  }

  for (let i = 0; i < target.length; i++) {
    if (target[i] !== null) {
      temp.push(target[i]);
      target[i] = null;

      Permutations(target, size - 1);

      target[i] = temp.pop();
    }
  }
}

Permutations([1, 2, 3], 2);
console.log(res);

When I run my code, I can see my res stores each permutation as it is is being executed. However, when I log it outside the function, all the stored value disappeared.

[ [ 1, 2 ] ]
[ [ 1, 3 ], [ 1, 3 ] ]
[ [ 2, 1 ], [ 2, 1 ], [ 2, 1 ] ]
[ [ 2, 3 ], [ 2, 3 ], [ 2, 3 ], [ 2, 3 ] ]
[ [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ] ]
[ [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ] ]
[ [], [], [], [], [], [] ]   // This is my console.log outside the function
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The array temp holds is the same array throughout the complete execution of your code. And res.push(temp); adds this same array (not a copy of it) to your res array.

Here a related question about how Objects are handled in JavaScript: Is JavaScript a pass-by-reference or pass-by-value language?

So your code results in res having N times the same array.

You could copy the element stored in temp to a new array using [...temp], and push that to your res array.

var res = [];
var temp = [];

function Permutations(target, size) {
  if (size === 0) {
    res.push([...temp]);
    return;
  }

  for (let i = 0; i < target.length; i++) {
    if (target[i] !== null) {
      temp.push(target[i]);
      target[i] = null;

      Permutations(target, size - 1);

      target[i] = temp.pop();
    }
  }
}

Permutations([1, 2, 3], 2);
console.log(res);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!