0

I would like a suggestion on why my code isnt working. The idea is to select only three names from a the list of names randomly, but it can't return the same name twice. I think it is close but I'm missing something here. Any help would be appreciated

(function(){

  var randomNames = function(){
      var names = ["Jeffrey, Ronald, Superman, Lyndon, Alison"];
      var myNames = [];

      for (var i = 0; i < 3; i++){
          var newNames = Math.floor(Math.random() * names.length);
          var randomAllNames = names[newNames];
          names.splice(newNames, 1);
          myNames.push(names);
          console.log(myNames);
      }
         return randomAllNames;

  }; randomNames();
})();
2
  • 4
    Your array contains only one element - a list of names - rather than an element per name. Commented Dec 13, 2013 at 11:51
  • also you are adding the entire array of names into the myNames array each loop iteration Commented Dec 13, 2013 at 11:55

1 Answer 1

1

note the myNames.push(randomAllNames); also your array was just one long string

(function(){

  var randomNames = function(){
      var names = ["Jeffrey", "Ronald", "Superman", "Lyndon", "Alison"];
      var myNames = [];

      for (var i = 0; i < 3; i++){
          var newNames = Math.floor(Math.random() * names.length);
          var randomAllNames = names[newNames];
          names.splice(newNames, 1);
          myNames.push(randomAllNames);
          console.log(myNames);
      }
         return randomAllNames;

  }; randomNames();
})();
Sign up to request clarification or add additional context in comments.

3 Comments

Ahhh, dumb mistake!! When I console.log(myNames); it returns 3 separate arrays. Amy I returning the wrong variable? ["Alison"] main.js:19 ["Alison", "Ronald"] main.js:19 ["Alison", "Ronald", "Superman"]
yes, the inner function should return myNames and the last line should also be return randomNames() if you want to be able to use the result elsewhere
Yes, as I will be using the results to add to the HTML on the page. Each random name will appear in as a list item

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.