javascriptstringmerge

How to merge two strings alternatively in javascript?


given input str1 is "abc" and str2 is "def" output should be adbecf and given str1 = "ab" and str2 = "def" output should be adbef

my output has been:

merge('abc','def') "adbecfNaN"

merge('ab','def') "adbeundefinedf"

I have been attempting to filter undefined and NAN, but it's not working.

Here's my code:

function merge (str1, str2) {

  var a = str1.split("").filter(Boolean);

  var b = str2.split("");

  var mergedString = '';


  for(var i = 0; i <= a.length && i <= b.length; i++) {

       mergedString +=  a[i] + b[i];

    }

    return mergedString;

}

Solution

  • you need to use < and not <= in loop condition since array indexes are started from 0. That is why you are getting NaN. you can do something like this:

    function merge (str1, str2) {
    
      var a = str1.split("").filter(Boolean);
    
      var b = str2.split("");
    
      var mergedString = '';
    
    
      for(var i = 0; i < a.length || i < b.length; i++) {  //loop condition checks if i is less than a.length or b.length
       if(i < a.length)  //if i is less than a.length add a[i] to string first.
         mergedString +=  a[i];
       if(i < b.length)  //if i is less than b.length add b[i] to string.
         mergedString +=  b[i];
      }
    return mergedString;
    
    }
    console.log(merge('abc','def'));
    console.log(merge('ab','def'));