Computer >> Computer tutorials >  >> Programming >> Javascript

Picking index randomly from array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of Numbers, arr, which possibly contains duplicates as the first argument and an Integer which exists in the array as the second argument.

The function should return an index at which the number exists in the array and since the number might exist for more than once in the array, we have to randomly pick one index and return that index.

For example, if the input to the function is −

const arr = [5, 3, 6, 7, 3, 4, 2, 3];
const num = 3;

Then the output should be −

const output = 4;

Output Explanation:

The number 3 exists at the index 1, 4 and 7 in the array, and since we have to pick any index randomly, so the output can be any of 1.

Example

The code for this will be −

const arr = [5, 3, 6, 7, 3, 4, 2, 3];
const num = 3;
Array.prototype.pick = function(target) {
   const targets = []
   this.findTarget(0, this.length, target, targets);
   return targets[Math.floor(Math.random() * targets.length)];
};
Array.prototype.findTarget = function(start, end, target, targets) {
   if(start + 1 === end || start === end) {
      if(this[start] === target) targets.push(start);
      return;
   }
   let j = start + Math.floor((end - start)/2);
   this.findTarget(start, j, target, targets);
   this.findTarget(j, end, target, targets);
};
console.log(arr.pick(num));

Output

The output in the console will be −

4