I'm wanting to merge 2 arrays with alternate values.
For example, these are my 2 arrays:
array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
array2 = [1, 2, 3],
The output I'm wanting is 4 from the 'array1', then 1 from 'array2'
result = ["a", "b", "c", "d", 1 , "e", "f", "g", "h", 2 , "i", "j" , 3]
This is the code I've got so far, however it outputs:
result = ["a", 1, "b", 2, "c", 3, "d", 4, "e", "f", "g", "h", "i", "j"]
var array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
array2 = [1, 2, 3, 4],
result = [],
i;
for (i = 0; i < array1.length; i ) {
result.push(array1[i]);
if (array2[i]) result.push(array2[i]);
}
console.log(result);
is anyone able to nudge me in the right direction?
Thanks in advance!
CodePudding user response:
You can use Array#flatMap
on the shorter array.
let array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"], array2 = [1, 2, 3];
let res = array2.flatMap((x, i) => array1.slice(i * 4, i * 4 4).concat(x));
console.log(JSON.stringify(res));
CodePudding user response:
You could slice the arrays.
const
array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
array2 = [1, 2, 3],
result = [];
let i = 0,
j = 0;
while (i < array1.length) {
result.push(
...array1.slice(i, i = 4),
...array2.slice(j, j = 1)
);
}
console.log(...result);
CodePudding user response:
If you need to zip two arrays together, you will need to figure out which is the longer, and which is the shorter. After you figure out which is which, you can calculate the step.
The following is a more traditional; algorithmic approach:
const zipArrays = (a, b) => {
const
longer = a.length > b.length ? a : b,
shorter = a === longer ? b : a,
step = Math.ceil(longer.length / shorter.length); // Round-up
let result = [], i = 0, j = 0;
for (i = 0; i < longer.length; i ) {
result.push(longer[i]);
if (i % step === step - 1) result.push(shorter[j ]);
}
if (j < shorter.length) {
result.push(shorter[j]); // See if we missed the last one
}
return result;
};
const
array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
array2 = [1, 2, 3];
console.log(...zipArrays(array1, array2));
.as-console-wrapper { top: 0; max-height: 100% !important; }