Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have to generate a array of length 3 says [3,2,1].. by random from the array of length 4 says [1,2,3,4] using java script.

  var ele=[1,2,3,4];

I have to generate a new array var three=new Array(3);

the value of the array "three" should be randomized without duplicate from array "ele" .

 ex three=[3,2,4]... 

Here is the code I tried,

var tempArray=[1,2,3,4];
var set_bf =[];
for(var k=0;k<tempArray.length;k++){
    var rand=(Math.round((Math.random()*tempArray.length)));
    set_bf.push(rand);
    console.log('male :'+rand);
    var idx = tempArray.indexOf(rand);
    if(idx!=-1) tempArray.splice(idx, 1);
}
share|improve this question
    
What have you tried? Where are you running into trouble? What's your best effort look like? SO isn't a code writing service. :-) –  T.J. Crowder Nov 8 '11 at 15:01
    
yes the array "three" should be created once from the "ele" –  Nithish Nov 8 '11 at 15:03
    
chk the code that i have tried its randomize the same –  Nithish Nov 8 '11 at 15:09

1 Answer 1

I think you want to select random entries from another array ?

var rand = myArray[Math.floor(Math.random() * myArray.length)];

This will give you a random element from the array myArray That should at least point you in the right direction

share|improve this answer
    
can you check my code above –  Nithish Nov 8 '11 at 15:06
    
@Nithish What does it do wrong ? –  ManseUK Nov 8 '11 at 15:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.