Skip to content
Advertisement

javascript merge 2 arrays with undefined elements

Hello I need a little help with js i have 2 arrays

const a = ['link1','link2','link3','link4','link5']
const b = ['link11','link22',undefined,'link44',undefined]

how can I replace the elements of a with b with ignoring the undefined index so the output would be

a = ['link11','link22','link3','link44','link5'] 

I tried to do it like this

  Array.prototype.splice.apply(
    a,
    [0, b.length].concat(b)
  );

but I got the array b back

Advertisement

Answer

You can iterate over array a using array#map and then extract the values from array b based on the index value. For undefined value, we can use the value in array a.

const a = ['link1','link2','link3','link4','link5'],
      b = ['link11','link22',undefined,'link44',undefined],
      result = a.map((link,i) => b[i] || link);
console.log(result);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement