1

Originally I was using the following to swap the values of 2 variables at random when the page loaded:

    var value1 = 260;
    var value2 = 325;
    var chosenValue = Math.random() < 0.5 ? value1 : value2;
    if (value1 == chosenValue) { var val = value1; } else { var val = value2; }
    if (value1 == chosenValue) { var val2 = value2; } else { var val2 = value1; }

However now I need to swap out 4 values and I no idea how to go about doing that.

    var value1 = 260;
    var value2 = 325;
    var value3 = 195;
    var value4 = 130;

Note that each value must be used only once and must be displayed in random order each time page is loaded.

help?

Bruce
  • 1,039
  • 1
  • 9
  • 31

3 Answers3

1

Here is a solution using splice:

Creating an array (arrayValues) with all the values (using concat), we use splice to remove a random value and, since splice modifies the source array, no value is repeated.

var value1 = 260;
var value2 = 325;
var value3 = 195;
var value4 = 130;

var arrayValues = [].concat(value1, value2, value3, value4);

value1 = arrayValues.splice(Math.floor(Math.random()*arrayValues.length), 1);
value2 = arrayValues.splice(Math.floor(Math.random()*arrayValues.length), 1);
value3 = arrayValues.splice(Math.floor(Math.random()*arrayValues.length), 1);
value4 = arrayValues.splice(Math.floor(Math.random()*arrayValues.length), 1);

console.log("value1: " + value1 + ", value2: "+ value2+ ", value3: " + value3 + ", value 4: " + value4)
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • 1
    Thank you, I voted you up and marked you correct because you gave working example AND explained it :) – Bruce Aug 12 '16 at 08:26
0

You can add all values to array, shuffle it (How to randomize (shuffle) a JavaScript array?) and then simple write value1 = arr[0] value2 = arr[1] etc..

Community
  • 1
  • 1
vitin
  • 1
  • 1
0

var randomValues = [260, 325, 195, 130].sort(function() {
    return .5 - Math.random();
});

// Array with the new random values
console.log(randomValues);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46