How to Select 3 Unique Items From A Dynamic Array
Ad
I have a Dynamic array which a sample of that looks like
var nums=[25,12,23,47,55,116,17,80,92,150,191,142,13,124,15,176,187,18,19,20,21,30,31];
Can you please let me know how I can select 3 unique items from the nums
and load them to a new array using jQuery of pure JS?
I tried this already
var arr = []
while(arr.length < 3){
var randomnumber=Math.ceil(Math.random()*nums.length)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
but I am not getting what I want
Ad
Answer
Ad
while (arr.length < 3) {
var randomIndex = Math.floor(Math.random()*nums.length);
if (arr.indexOf(nums[randomIndex]) === -1) {
arr.push(nums[randomIndex])
}
}
Here I create a new random index each time we go through the loop, and then check if that number is already in our result array. If it is not, we push it in, otherwise we just start over.
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad