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];
}
1
  • 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. Commented Mar 11, 2016 at 14:35

2 Answers 2

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

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

2 Comments

You beat me to it! I made a Fiddle that demonstrates this technique: jsfiddle.net/xhy38o5g
@PostCrafter Thank You so much,exactly what i need
-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);
}

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.