I have:
array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
array2 = ['a', 'b', 'c'];
I got the concat of arrays working, but only one at a time:
var alternatingArrayResult = [array1, array2].reduce(function (r, a) {
return a.forEach(function (a, i) {
return (r[i] = r[i] || []).push(a);
}), r;
}, []).reduce(function (a, b) {
return a.concat(b);
});
// => alternatingArrayResult = [1, 'a', 2, 'b', 3, 'c', 4, 5, 6, 7, 8, 9];
I want to add two items from array 1, then one from array 2 - and so on.
Desired output:
result = [1, 2, 'a', 3, 4, 'b', 5, 6, 'c', 7, 8, 9];
var array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var array2 = ['a', 'b', 'c'];
var alternatingResultArray = [array1, array2].reduce(function (r, a) {
return a.forEach(function (a, i) {
return (r[i] = r[i] || []).push(a);
}), r;
}, []).reduce(function (a, b) {
return a.concat(b);
});
console.log(alternatingResultArray);
You could get a lenght and iterate the parts for pushing.
const
array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9],
array2 = ['a', 'b', 'c'],
result = [];
for (i = 0, l = Math.max(Math.ceil(array1.length / 2), array2.length); i < l; i++) {
result.push(
...array1.slice(i * 2, (i + 1) * 2),
...array2.slice(i, i + 1),
);
}
console.log(...result);
A more abstact version with size of the wanted subarrays.
const
array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9],
array2 = ['a', 'b', 'c'],
data = [array1, array2],
sizes = [2, 1]
result = [];
for (i = 0, l = Math.max(...data.map(({ length }, i) => Math.ceil(length / sizes[i]))); i < l; i++) {
data.forEach((a, j) => result.push(...a.slice(i * sizes[j], (i + 1) * sizes[j])));
}
console.log(...result);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments