- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Picking out uniques from an array in JavaScript
- Picking the largest elements from multidimensional array in JavaScript
- How to exclude certain values from randomly generated array JavaScript
- Picking all elements whose value is equal to index in JavaScript
- Randomly shuffling an array of literals in JavaScript
- Maximum area rectangle by picking four sides from array in C++
- Changing color randomly in JavaScript
- Picking the odd one out in JavaScript
- Find closest index of array in JavaScript
- Array index to balance sums in JavaScript
- Finding median index of array in JavaScript
- Reverse index value sum of array in JavaScript
- Sort by index of an array in JavaScript
- Function to choose elements randomly in JavaScript
- JavaScript to push value in empty index in array

Advertisements