5

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;

}
Dij
  • 9,641
  • 4
  • 16
  • 34
raj jar
  • 55
  • 1
  • 4
  • `a[i]` is `undefined` when `i == a.length`; you want `i < a.length` instead of `<=`. – Ry- Sep 06 '17 at 05:09
  • I tried that suggestion and my output was merge('ab','def') "adbe." I'm still missing the "f". – raj jar Sep 06 '17 at 05:17

9 Answers9

2

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'));
Dij
  • 9,641
  • 4
  • 16
  • 34
2

The shortest way and probably the fastest, is to iterate the smallest length of the string and then take the rest of both string.

function zip(a, b) {
    var i,
        l = Math.min(a.length, b.length),
        temp = '';

    for( i = 0; i < l; i++) {
        temp += a[i] + b[i];
    }
    return temp + a.slice(i) + b.slice(i);
}

console.log(zip('abc', '123')); // a1b2c3
console.log(zip('ab', '123'));  // a1b23
console.log(zip('abcd', '12')); // a1b2cd

With ES6, you could use Array.from with the built in mapper for the letters.

var a = "ab",
    b = "def",
    result = Array.from(a.length > b.length ? a : b, (_, i) => (a[i] || "") + (b[i] || ""))
                  .join('');

console.log(result);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
1

A simple approach: Iterate over the longest string, output the combination of the characters at the current index, use the empty string if no character exists at the current index.

console.log(merge('ab','def'));

function merge(a, b){
  for(var i = 0, s = '', l = Math.max(a.length, b.length); i < l; i++){
    s += a.charAt(i) || '';
    s += b.charAt(i) || '';
  }
  return s;
}
Tomas Langkaas
  • 4,234
  • 1
  • 16
  • 32
1

const merge = (str1, str2) => str1.length && `${str1[0]}${merge(str2, str1.slice(1))}` || str2;

console.log(merge('abc','def'));
console.log(merge('ab','def'));
0

JS bin link -https://jsbin.com/nihoxivoxa/edit?js,console

function merge (str1, str2) {

  var a = str1.split("");

  var b = str2.split("");
  
  var count = 0;
  
  var merged_string = "";
  //let's determine the loop counts, which depends on the smaller length of string
  
  a.length < b.length ? count = a.length: count = b.length;
  
  
  for( var i=0; i< count; i++){
    merged_string += a[i]+b[i];
    
  }
  
  // add remaining characters

    count < str1.length 
    ? merged_string += str1.substr(count, str1.length)
    : merged_string += str2.substr(count, str2.length)

  
  return merged_string;

 
}
console.log(merge('ab','xysfergtrhyhn'))
Anish K.
  • 2,192
  • 3
  • 16
  • 24
0
function merge(s1, s2) {
  var result = "";
  for(var i=0; i<s1.length && i<s2.length; i++){
   result+=s1[i]+s2[i];
  }
 s1.length<s2.length?result+=s2.substr(s1.length):result+=s1.substr(s2.length)
 return result;
}
console.log(merge("abc","12345"));
console.log(merge("12345","abc"));
L4reds
  • 402
  • 2
  • 5
  • 20
0

If you convert the strings to arrays, you can recursively shift the first element off of each array onto a new array, then continue until there are no elements left in both arrays, finally returning the new array.

const shift = (a, b) => a.length||b.length?[a.shift(), b.shift(), ...shift(a,b)]:[];

console.log(shift([...'acegik'],[...'bdfhjl']).join('')); // abcdefghijkl
console.log(shift([...'aceg'  ],[...'bdfhjl']).join('')); // abcdefghjl
console.log(shift([...'acegik'],[...'bdfh'  ]).join('')); // abcdefghik
0

With Lodash in ES6, it is possible to solve this problem in one line code:

_.zip('abc'.split(''), 'def'.split('')).reduce((prev, curr) => prev + curr.join(''), '');

Here, zip function is provided by a node library called Lodash, which can be installed from npm: https://lodash.com/

千木郷
  • 1,197
  • 1
  • 17
  • 26
0

Here is a small function that will break down two strings to produce an array of characters in the same alternating sequence you described. You can then use join('') to combine these characters into one string.

var m = (a, b) => a.length ? [a[0], ...m(b, a.slice(1))] : b;
var string1 = "SCE ESG!";
var string2 = "ERTMSAE";
var mix = m(string1, string2);

console.log(mix.join(''));

or if you need it to work for any number of input strings:

    var m = (a = [], ...b) => 
        b.length ? a.length ? [a[0], ...m(...b, a.slice(1))] : m(...b) : a;
    var string1 = "SR SG";
    var string2 = "EEMSE";
    var string3 = "CTEA!";
    var mix = m(string1, string2, string3);

    console.log(mix.join(''));
omikes
  • 7,248
  • 8
  • 36
  • 47