0

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;
    });
}
ckhedda
  • 73
  • 1
  • 7

6 Answers6

1

You can loop through setting a random variable. I'm assuming you don't want duplicates so you also splice the array (and base the random value based on the length of the original array)

function navn () {
      var arr = ["Hans","Ole","Nils","Olav","Per","Knut","Kari","Line","Pia"];
      let return_arr = [];
     for (let i = 0; i < 3; i++) {
        var random_int = Math.round(Math.random()*(arr.length -1));
        return_arr.push(arr[random_int]);
        arr.splice(random_int, 1);
     }
     return return_arr;
}

console.log(navn());
chevybow
  • 9,959
  • 6
  • 24
  • 39
0

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));
Danmoreng
  • 2,367
  • 1
  • 19
  • 32
0

You can generate a Set of three random indices and get the elements at that index (Set ensures no duplicates).

function navn() {
  var arr = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"];

  var randomIndices = new Set();
  while (randomIndices.size < 3) {
    randomIndices.add(Math.floor(Math.random() * arr.length));
  }

  var nyArr = [...randomIndices].map(function(i) {
    return arr[i];
  });

  return nyArr;
}

console.log(navn());
console.log(navn());
console.log(navn());
slider
  • 12,810
  • 1
  • 26
  • 42
0

You can reduce the input array to a subset by splicing the input array's values into a new array:

var a = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"];

const navn = (arr, count) => {
  return arr.reduce((acc, val) => {
    // Get a ~ random number
    let rand = Math.floor(Math.random() * Math.floor(count));
    // Extract the corresponding element, into our accumulator
    acc.length < count && (acc.push(arr.splice(rand, 1)[0]));

    return acc;
  }, []);
}

// Test
console.dir(navn(a, 3));
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
0

Here's an ES6+ function. You take in any array and the number of random values you want and it'll spit them out without duplicates and prevent improper use of the function by disallowing a number greater than the number of unique values.

 random = (arr, n) => {
    let l = [...new Set(arr)].length, res = new Set(), r = () => arr[Math.random() * l | 0]
    if (n > l) throw new Error("length is greater than n unique values");
    while (res.size < n) res.add(r());
    return [...res];
  }

let arr = ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"];

  random = (arr, n) => {
    let l = [...new Set(arr)].length, res = new Set(), r = () => arr[Math.random() * l | 0]
    if (n > l) throw new Error("length is greater than n unique values");
    while (res.size < n) res.add(r());
    return [...res];
  }

console.log(random(arr, 9));
console.log(random(arr, 5));
zfrisch
  • 8,474
  • 1
  • 22
  • 34
-1

You can include underscore or lodash in your project. Then you can simply use this:

_.sample( ["Hans", "Ole", "Nils", "Olav", "Per", "Knut", "Kari", "Line", "Pia"], 3);

or you can also use the _.sampleSize method in lodash:

_.sampleSize(['January', 'February', 'March'], 3);

Both will give you 3 random elements.

Azizul Hakim
  • 154
  • 5