Search code examples
javascriptarraysarr

Push 3 random names into a new Array


I cant get the following code to return 3 random names from that array, any suggestions? (The duplicate question didn't adress my problem, hence my problem is 3 values instead of 1 value.)

function navn() {
    var arr = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"];
    var nyArr = arr.filter(function (number) {
        return number % 3 === 0;
    });
}

Solution

  • There are different possibilities to solve this, another thing which isn't mentioned in the question: should those 3 names be unique or can duplicates happen?

    right now all solutions including this one can have the name twice or even three times in the result array.

    Additionally I split the code up in several functions, and made one where you can input an array of values and an amount of how many random values you want to get from it back:

        var arr = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"];
        
        function getRandomNames(arr, amount){
          var result = [];
          for(var i = 0; i < amount; i++){
            result.push(arr[getRandomIndex(arr.length)]);
          }
          return result;
        }
        
        function getRandomIndex(maxIndex){
          return Math.floor(Math.random() * maxIndex);
        }
        
        console.log(getRandomNames(arr, 3));