随机化并拆分对象为2个数组

Randomize and split object into 2 arrays

本文关键字:2个 数组 对象 拆分 随机化      更新时间:2023-09-26

我有一个对象,有8个项目-我想把这些项目分成2个数组(随机)。

我想要实现的:

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

From object,它应该自动创建2个单独的数组,并将对象项随机分配到数组中。确保它不会重复。

array 1: [3,5,6]

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

确保对象变量是一个数组。Var element =[…];不确定您是否有将工作:var元素={…你的物品…};您可以使用这段代码来洗牌您的数组(事实上的无偏洗牌算法是Fisher-Yates (aka Knuth) shuffle .):如何随机(洗牌)一个JavaScript数组?

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;
}

然后像这样将它拼接(将数组拼接成两半,无论大小?):

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

原始数组将包含剩余的值

你的if逻辑没有意义。

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

Math.random()将得到0(包含)到1(不包含)之间的任何值。http://www.w3schools.com/jsref/jsref_random.asp

你的函数没有做任何事情来创建随机值的数组。