I want to create a function that takes two different arrays and iterates them, the output should be a new array containing both one by one, and if they have different lengths, keep on pushing the rest of the longest one. I've tried this:
function mergeArrays(firstArray, secondArray) {
let newArray = []
firstArray.forEach((element, index) => {
newArray.push(element, secondArray[index])
});
return newArray
}
If I entered this:
mergeArrays(["a", "b"], [1, 2, 3, 4])
Output should be ["a", 1, "b", 2, 3, 4]
, instead it is stopping in this case when the length of the first one ends, or if i switched between first and second arrays as parameters, it would keep on pushing the first but in the second it would push undefined
.
How can I fix it?