0

I have one Question

  • Write a Javascript code to store a list of strings/sort it and print it in an unordered list

could you please tell me how to print unordered list in javascript ? I do like this use Math.random function but it is not printing the value

var arr=['abc','pqr','mnc'];
for(var i=0;i<arr.length;i++){
  console.log(arr[Math.floor((Math.random() * 3) + 1)]) ; 

}

http://jsfiddle.net/3s4Lqr0o/1/ It is not printing the all values?

user944513
  • 12,247
  • 49
  • 168
  • 318

1 Answers1

1

The first problem here is that Math.floor((Math.random() * 3) + 1) will return a number between 1 to 3. Your array only has elements at index 0, 1, and 2. So abc won't be printed at all.

The second problem is, there is no guarantee that your calculation will return every single number 0, 1 and 2 exactly once. You could be getting arr[1] three times in a row, resulting in pqr being printed 3 times.

I initially voted to mark this question as a duplicate of How to randomize (shuffle) a JavaScript array?. My thought was that you can simply shuffle the array, then print the shuffled array. However, since this question has been reopened, I will propose an alternate solution.

arr = ['abc','pqr','mnc'];

while (arr.length > 0) {
    var index = Math.floor(Math.random() * arr.length);
    console.log(arr[index]);
    arr.splice(index, 1);
}

Randomly select one element in the array, print it and then remove it from the array. Repeat until there are no more elements.

Community
  • 1
  • 1
Zsw
  • 3,920
  • 4
  • 29
  • 43
  • Amadan does bring up a good point in the comments. I simply took the question at face value, but his points are worth considering. – Zsw Sep 25 '15 at 03:29