将对象的随机数组分成两个相等的数组

伊夫·基彭多(Yves Kipondo)

我有这个对象数组;

let persons = [
    {id: 1, name: "..."},
    {id: 2, name: "..."},
    {id: 3, name: "..."},
    {id: 4, name: "..."},
    {id: 5, name: "..."},
    {id: 6, name: "..."},
    {id: 7, name: "..."},
    {id: 8, name: "..."}
]

我想将此数组拆分为两个相等长度的数组。每次执行拆分数组的函数时,它应该在每个数组中返回一个不相同的对象列表的随机数据。

我尝试使用此功能

function splitArr(data, part) {
    let list1 = [];
    let list2 = [];
    for(let i = 0; i < data.length ; i++) {
        let random = Math.floor(Math.random() * data.length);
        if(random % 2 === 0) {
            list1.push(data[i]);
        } else {
            list2.push(data[i]);
        }

    }
    return [list1, list2];
}

显然函数每次都将返回完全相同长度的数组。有时它返回的2和6元素数组不相等。

在此处输入图片说明

亭子

随机随机排列阵列,然后将其对接一半。

对于改组数组,请采用此处提供的解决方案

function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

为了从中获取两个列表,请执行以下操作:

let list2 = shuffle([...data]); // spread to avoid mutating the original
let list1 = list2.splice(0, data.length >> 1); 

移位运算符>>用于获取数组长度的截断一半。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章