Merge And Alternate 2 Arrays Into Single Array
I have beginner scripting skills and am using a form of JavaScript, ECMA-262 that is found in a program called Opus Pro (Digital Workshop, UK). I've been searching online, without
Solution 1:
ECMA-262 has the Array object which has the .push()
method. You can see it yourself in the ECMA spec in section 15.4.4.7.
To merge two arrays by alternating between random elements from each array, you can do this:
functionmergeTwoRandom(arr1, arr2) {
functionextractRandom(arr) {
var index = Math.floor(Math.random() * arr.length);
var result = arr[index];
// remove item from the array
arr.splice(index, 1);
return(result);
}
var result = [];
while (arr1.length || arr2.length) {
if (arr1.length) {
result.push(extractRandom(arr1));
}
if (arr2.length){
result.push(extractRandom(arr2));
}
}
return(result);
}
If you want to do it without .push()
, you can do it like this:
functionmergeTwoRandom(arr1, arr2) {
functionextractRandom(arr) {
var index = Math.floor(Math.random() * arr.length);
var result = arr[index];
// remove item from the array
arr.splice(index, 1);
return(result);
}
var result = [];
while (arr1.length || arr2.length) {
if (arr1.length) {
result[result.length] = extractRandom(arr1);
}
if (arr2.length){
result[result.length] = extractRandom(arr2);
}
}
return(result);
}
If you also don't have .splice()
, you can do it like this:
functionmergeTwoRandom(arr1, arr2) {
functionremoveItem(arr, index) {
for (var i = index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr.length = arr.length - 1;
}
functionextractRandom(arr) {
var index = Math.floor(Math.random() * arr.length);
var result = arr[index];
// remove item from the arrayremoveItem(arr, index);
return(result);
}
var result = [];
while (arr1.length || arr2.length) {
if (arr1.length) {
result[result.length] = extractRandom(arr1);
}
if (arr2.length){
result[result.length] = extractRandom(arr2);
}
}
return(result);
}
Post a Comment for "Merge And Alternate 2 Arrays Into Single Array"