I am facing a challenge with an array of objects;
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: "..."}
]
My goal is to divide this array into two equal-length arrays and have different random data in each array every time the function is executed, not the same set of objects.
I attempted to achieve this using the following function:
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];
}
However, it is not guaranteed that the function will always return two arrays of equal length. Sometimes it returns arrays with 2 and 6 elements, which is not what I intended.