0

I have an object with 8 items - i want to split those items up into 2 arrays (randomised).

What i want to achieve:

object: {1, 2, 3, 4, 5, 6} : harcoded

From object, it should automatically create 2 separate arrays and take object items and randomise them into the array. Making sure that it does not repeat.

array 1: [3, 5, 6]

array 2: [2, 1, 4]

Code so far:

var element = {
  1: {
    "name": "One element",
    "other": 10
  },
  2: {
    "name": "Two element",
    "other": 20
  },
  3: {
    "name": "Three element",
    "other": 30
  },
  4: {
    "name": "Four element",
    "other": 40
  },
  5: {
    "name": "Five element",
    "other": 50
  },
  6: {
    "name": "Six element",
    "other": 60
  },
  7: {
    "name": "Seven element",
    "other": 70
  },
  8: {
    "name": "Eight element",
    "other": 80
  }
};

function pickRandomProperty(obj) {
  var result;
  var count = 0;
  for (var prop in obj)
    if (Math.random() < 1 / ++count)
      result = prop;
  return result;
}



console.log(pickRandomProperty(element));
Chad McGrath
  • 1,561
  • 1
  • 11
  • 17
jagmitg
  • 4,236
  • 7
  • 25
  • 59

2 Answers2

1

Make sure your object variable is an array. var element = [...youritems]; not sure if what you have will work: var element = {...your items...}; You can use this code to shuffle your array (The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.): How to randomize (shuffle) a JavaScript array?

function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;  
while (0 !== currentIndex) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}

Then splice it like this (Splice an array in half, no matter the size?):

    var half_length = Math.ceil(arrayName.length / 2);    
    var leftSide = arrayName.splice(0,half_length);

Your original array will contain the remaining values.

Community
  • 1
  • 1
Chad McGrath
  • 1,561
  • 1
  • 11
  • 17
-2

Your if logic doesn't make sense.

if (Math.random() < 1 / ++count)

The Math.random() will result any value between 0 (inclusive) and 1 (exclusive). http://www.w3schools.com/jsref/jsref_random.asp

Your function is not doing anything to create arrays with the random values.

Samuel
  • 1