0

At first I want to metion that I know how to solve this task with array.sort and it is most acceptable way. But I want to understand why my actions failed. So I have 2 arrays - v_a, whuch consists from 3 values - '1','2','3' and empty array v_a_resorted, where I want to store v_a values arranged in random order. So, logicaly, I get random value in v_a, splice it in v_a, and push it to v_a_resoreted. Without For it looks for me in this way:

 var v_a = new Array ('1','2','3');
 var v_a_resorted = [];
 var v_a_l = v_a.length;
 var r_v_a_n = Math.floor(Math.random() * (v_a_l - 0+0)) + 0;
 v_a.splice(r_v_a_n, 1);
 v_a_resorted.push(v_a[r_v_a_n]);
 document.write("<b>Random number</b> -" + r_v_a_n + "<br>"); 
 document.write("<b>Transportation unit</b> -" + v_a[r_v_a_n] + "<br>");
 document.write("<b>Old Array</b> -" + v_a + "<br>"); 
 document.write("<b>New Array</b> -" + v_a_resorted + "<br>"); 

But it doesn't work. E.g. if Random number = 1, than Transportation unit = 2 and old array = 1,3 and new array = 2. But in my case it's: Random number = 1, Transportation unit=3, Old array = 1,3 and New Array = 3.

But why?

Cove
  • 655
  • 3
  • 7
  • 17
  • 3
    It might make it easier for people to read if you rename your variables. Instead of letters, use words. `arrayLength`, `sortedArray` etc. – Matt Lishman Jun 02 '16 at 13:25
  • ^agreed. They're actually quite distracting in a weird way. – mferly Jun 02 '16 at 13:27
  • Possible duplicate of [How to randomize (shuffle) a JavaScript array?](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – Meow Jun 02 '16 at 14:10

2 Answers2

1

Seems like you remove an element from the first array and try to push it (being already removed with splice) to the second one
Changing splice and push calls does what you are trying to achieve

 var v_a = new Array ('1','2','3');
 var v_a_resorted = [];
 var v_a_l = v_a.length;
 var r_v_a_n = Math.floor(Math.random() * (v_a_l - 0+0)) + 0;
    document.write("<b>Random number</b> -" + r_v_a_n + "<br>"); 
 document.write("<b>Transportation unit</b> -" + v_a[r_v_a_n] + "<br>");
 v_a_resorted.push(v_a[r_v_a_n]);//this line
    v_a.splice(r_v_a_n, 1);//and this one     
 
 document.write("<b>Old Array</b> -" + v_a + "<br>"); 
 document.write("<b>New Array</b> -" + v_a_resorted + "<br>"); 
www0z0k
  • 4,444
  • 3
  • 27
  • 32
0

I believe this question was answered in another post.

How to randomize (shuffle) a JavaScript array?

Community
  • 1
  • 1
Meow
  • 1,610
  • 1
  • 14
  • 18