1

Okay, just learning JavaScript here, I know I should search for the answer, but I can't even figure out what I should search for, im completely lost as to why this is happening

  // string or array
 var strr=[1,5,3];
//changed array.
var cha=[];
var t=0;
/*push strr into the cha array
should look like
[
[1,5,3],
[1,5,3],
[1,5,3]
]
*/
for(var i=0;i<3;i++){
cha.push(strr);
}
//shuffle each element one by one
for(a in cha){
cha[a]=cha[a].sort(function()
    {return Math.floor(Math.random()*100)-50;
    });
}
//each element should be a re arranged array with the     same elemnts of strr
// Like 135, 351, 153 for example
console.log(cha);

// But it arranges all of the elements the same. the shuffle     changed the order of strr, but not each of cha...
// Like 351,351,351 for example, they are randomized, but all the same.
1
  • the array cha, is holding three references to the same array strr. if you want three separate strr arrays you need to clone them. cha.push(strr.slice(0)); Commented Mar 1, 2018 at 10:26

1 Answer 1

3

You are effectively pushing the same array thrice.

push a hollow copy of it (since it is an array of primitives)

cha.push( strr.slice() );

Demo

var strr = [1, 5, 3];
var cha = [];
var t = 0;
for (var i = 0; i < 3; i++) {
  cha.push(strr.slice());
}
for (a in cha) {
  cha[a] = cha[a].sort(function() {
    return Math.floor(Math.random() * 100) - 50;
  });
}
console.log(cha);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.