0

How do I set the value of my textarea containing all values from my array in random order? I currently have 2 issues:

  • If I loop through the array, it puts only one element into the textarea
  • I do not want elements to be duplicated

Here is my code

var area = document.getElementById('area');
var arr =['www.google.com','www.bing.com','www.yahoo.com','www.codecademy.com','twitter.com'
    ];    
var rand = arr[Math.floor(Math.random()*arr.length)];

for(var i in arr) {
    area.value = arr[i];
}
Randy
  • 9,419
  • 5
  • 39
  • 56
Viktor
  • 722
  • 1
  • 8
  • 25
  • 1
    Create another array and keep storing rand values in that array. And check your new rand value with the values in the new array to avoid printing duplicates. This is what I understand from your question. If this is not what you want then please explain more and try to post some more code or create a fiddle. – The Guest Mar 11 '16 at 14:35

2 Answers2

5

You actually just want to shuffle the array and then join the array with whatever you want.

For example use the shuffle function from this answer

/**
 * Shuffles array in place.
 * @param {Array} a items The array containing the items.
 * @return {Array} a The shuffled array
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i -= 1) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

Afterwards use it like this:

var area = document.getElementById('area');
var arr =['www.google.com','www.bing.com','www.yahoo.com','www.codecademy.com','twitter.com'];    
shuffle(arr);

area.value = arr.join(' '); // or with whatever you want to separate them

Check the jsfiddle example: here

Community
  • 1
  • 1
PostCrafter
  • 655
  • 5
  • 15
-1

You can try removing elements that are already printed by splicing them.

var origArr = arr;

for(var i in arr) {
    area.value = arr[i];
    arr.splice(i, 1);
}