0

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?

Fabrizio
  • 13
  • 1
  • 1
    Does this answer your question? [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Sysix Dec 03 '21 at 22:26

1 Answers1

0

maybe try this

const newArray = [];
for (let index = 0; index < firstArray.length || index < secondArray.length, index++) {
  // find out if firstArray[index] exists
  // find out if secondArray[index] exists
  // add them to newArray
}
Alex028502
  • 3,486
  • 2
  • 23
  • 50