http://codepen.io/anon/pen/BpBOoB
If you're new to JavaScript, the code on the linked CodePen uses ES6 syntax, specifically incorporating destructuring for array manipulation and distinguishing between const
and var
.
An important scenario not addressed in the existing answer is what happens when the parent arrays are of unequal lengths.
Merging two parents with different sizes using a simple iteration can result in loss of data from the longer parent or errors due to mismatched indices. To handle this, the code first sorts the parents by length, places the shortest as the first parent, creates the child array, and then appends any additional data from the longer parent to complete the child array.
const parentOne = ['j1','j2','j3','j4','j5'];
const parentTwo = ['j3','j4','j2','j1','j4'];
const parentThree = ['j1','j2','j3','j4','j5', '#', '##', '###'];
const parentFour = ['j3','j4','j2','j1','j4'];
const parentFive = ['j1','j2','j3','j4','j5', '#', '##', '###'];
const parentSix = ['j3','j4','j2','j1','j4'];
// Ensure parentOne is the shortest
const fn = (...parents) => {
// Ensure the shortest parent comes first
[parents] = parents[1].length < parents[0].length ? [[parents[1], parents[0]]] : [[parents[0], parents[1]]];
// Iterate over the shortest parent
let child = parents[0].map((item, i) => parents[Math.round(Math.random())][i]);
// Add remaining elements from the longest parent to the child
if (parents[1].length > parents[0].length) {
child = [...child, ...parents[1].slice(parents[0].length)];
}
return child;
}
console.log(fn(parentOne, parentTwo));
console.log(fn(parentThree, parentFour));
console.log(fn(parentFive, parentSix));
console.log('---');