2

can you please take a look at this demo and let me know how I can create 3 unique values from an array of numbers?

var num = [];
var chances = "0123456789";
for (var i = 0; i < 3; i++) {
  num.push(chances.charAt(Math.floor(Math.random() * chances.length)));
}

console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

4

2 Answers 2

2

You can do something like this

var num = [];
for (var i = 0; i < 3;) {
  var ran = Math.floor(Math.random() * 10);
  //  You can generate random number between 0-9 using this , suggested by @Tushar
  if (num.indexOf(ran) == -1)
  // check number is already in array
    num[i++] = ran;
    // if not then push the value and increment i
}

document.write(num.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

For getting unique alphabets

var res = [],
  alp = 'abcdefghijklmnopqrstuvwxyz'.split('');
  // creating an array of alphabets for picking alphabers
for (var i = 0; i < 3;) {
  var ran = Math.floor(Math.random() * 26);
  //  You can generate random number between 0-25 using this
  if (res.indexOf(alp[ran]) == -1)
  // check alphabet is already in array
    res[i++] = alp[ran];
  // if not then push the value and increment i
}

document.write(res.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or

var res = [],
  alp = 'abcdefghijklmnopqrstuvwxyz'.split('');
  // creating an array of alphabets for picking alphabers
for (var i = 0; i < 3;) {
  var ran = Math.floor(Math.random() * 10000) % 26;
  //  You can generate random number between 0-25 using this
  if (res.indexOf(alp[ran]) == -1)
  // check alphabet is already in array
    res[i++] = alp[ran];
  // if not then push the value and increment i
}

document.write(res.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Pranav C Balan, can you also let me know hoe to get 3 unique letter from alphabet as well?
That's a nice work-around @Behseini but keep in mind this does not generate random unique numbers, this'll just pick unique numbers from random numbers
@Behseini You cannot generate random numbers that are unique.
Ok I think I understand what you are saying now
0

You may also try this code:

var num = [];
var chances = "0123456789";
var len = chances.length;
var str;
while (num.length < 3) {
  str = "";
  while (str.length < len)
    str += chances[Math.floor((Math.random() * len) % len)];
  if (-1 === num.indexOf(str))
    num.push(str);
}
document.write(JSON.stringify(num));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.