2016-09-16 78 views
1

我有一個包含8個項目的對象 - 我想將這些項目拆分成2個數組(隨機化)。隨機化並將對象拆分爲2個數組

我想要實現什麼:

對象:{1,2,3,4,5,6}:harcoded

從對象時,它會自動創建2個獨立的陣列和取對象項並將它們隨機放入數組中。確保它不重複。

陣列1:[3,5,6]

陣列2:[2,1,4]

代碼到目前爲止:

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)); 
+0

你怎麼得到隨機元素? –

+0

你目前的代碼有什麼問題;什麼是正確的,什麼是錯的? –

+0

上面的代碼沒有錯,我只是需要幫助試圖將對象分成2個數組,如上面所示的示例。找出最好的方法 –

回答

1

確保您對象變量是一個數組。 var element = [... youritems]; 不知道你有什麼會工作:var element = {...你的項目...}; 您可以使用此代碼來打亂你的數組(事實上的公正洗牌算法是費雪耶茨(又名高德納)洗牌。):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; 
} 

然後拼接像這樣(Splice an array in half, no matter the size?):

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

您的原始數組將包含剩餘的值。

+0

謝謝,但這並沒有讓它隨機化。 –

+0

這個答案有2個部分。您是否在第一個鏈接中嘗試了洗牌代碼?我將編輯以包含它。 –

-2

你的if邏輯沒有意義。

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

的的Math.random()將導致介於0(含)和1(不包括)的任何值。 http://www.w3schools.com/jsref/jsref_random.asp

您的函數沒有做任何事情來創建具有隨機值的數組。