Sophie Rhodes - 1 year ago 103
Javascript Question

# Randomize and split object into 2 arrays

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));
``````

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download