Merge two arrays with whitespace

Asked

Viewed 72 times

2

I have two arrays:

const array1 = ['lorem','ipsum','teste','','hello','','vol']
const array2 = ['lorem','ipsum','teste','array2Tes','','world','vol']

How do I merge the empty parts of the first array with the filled parts of the second array at the same position. At position 3 of the array1 is empty , but in that same position of array2 is filled with 'array2Tes'. E, at position 4 of the array2 is empty, but at that same position in array1 is filled with 'hello'. Would look like this:

const newArray = ['lorem','ipsum','teste','array2Tes','hello','world','vol']

How do I make this mixture?

  • 1

    The two arrays will always be the same size?

  • That. They will always have the msm size.

2 answers

5


If you look at the size of the arrays, the example is based on the informed Arrays.

const array1 = ['lorem','ipsum','teste','','hello','','vol']
const array2 = ['lorem','ipsum','teste','array2Tes','','world','vol']

array1.forEach((elemento, index ) => {
    elemento === '' ? array1[index] = array2[index] : '';   
})

console.log(array1)
  • The arrays will be bigger than this example I passed, but will always be the same size. I think your answer met the need. VLWSS

  • Yes, size is important, but inside the forEach you can do more validations.

  • 1

    Detail: inside the forEach you already own the element of array1 in elemento, you can save some operations by returning the value of it instead of fetching it again with array1[index].

  • Using the widget is not possible, but it is possible to callback the array in question. Example: array1.forEach((elemento, index, theArray) => {
 elemento === '' ? theArray[index] = array2[index] : ''; 
})

3

Another way is by using .map() creating a new array:

const array1 = ['lorem','ipsum','teste','','hello','','vol']
const array2 = ['lorem','ipsum','teste','array2Tes','','world','vol']

const newArray = array1.map( (e,i) => { return !e ? array2[i] : array1[i] } );

console.log(newArray);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.