-4

I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?

For example:

var a = "abc"
var b = "def"

result = "adbecf"

6 Answers6

1

The best way to do this is to perform the following algorithm:

  1. Iterate through string 1
  2. For each character, if there is a character in the same position in string 2, replace the original character with both

This can be achieved with the following code:

function merge(s, t) {
  return s.split("")
          .map(function(v,i) {
              return t[i] ? v + t[i] : v
          })
          .join("")
}

or the more Codegolf type answer:

s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``
bren
  • 4,176
  • 3
  • 28
  • 43
1

I would use Array.from to generate an array from the strings (unicode conscious).

After that, just add a letter from each string until there's no letters left in each. Please note this solution will combine strings of uneven length (aa+bbbb=ababbb)

var a = "abc"
var b = "def"
var d = "foo  bar mañana mañana"

function combineStrings(a,b){
  var c = "";
  a = Array.from(a);
  b = Array.from(b);
  while(a.length > 0 || b.length > 0){
    if(a.length > 0)
      c += a.splice(0,1);
    if(b.length > 0)
      c += b.splice(0,1);
  }
  return c;
}

var test = combineStrings(a,b);
console.log(test);

var test2 = combineStrings(a,d);
console.log(test2);
Hodrobond
  • 1,665
  • 17
  • 18
1

The simple way would be define the longest string and assigned to for loop. Also you have to add if statments for strings of uneven length, because you want to ignore undefined values of shorter string.

function mergeStrings(s1, s2){

   
  var n = s1.length;
  
  if(s1.length < s2.length){
    n = s2.length;
  }
  
  var string = '';
  for(var i = 0; i < n; i++){
    if(s1[i]){
      string += s1[i];
    }
    if(s2[i]){
      string += s2[i];
    }
  }

  return string;
}

console.log(mergeStrings('ab','lmnap'));
console.log(mergeStrings('abc','def'));
Arthur
  • 31
  • 3
0

If your strings are the same length, this will work. If not you'll have to append the rest of the longer string after the loop. You can declare i outside of the loop and then use substr() to get the end of the longer string.

const a = "abc"
const b = "def"

var res = "";
for (var i = 0;i < Math.min(a.length, b.length); i++) {
  res += a.charAt(i) + b.charAt(i)
}

console.log(res)
schrej
  • 450
  • 3
  • 10
0

Regex or array processing and joining do the job:

let a = 'abc';
let b = 'def';
console.log(a.replace(/./g, (c, i) => c + b[i]));        // 'adbecf'
console.log(Array.from(a, (c, i) => c + b[i]).join('')); // 'adbecf'
le_m
  • 19,302
  • 9
  • 64
  • 74
0

You can solve this using array spread and reduce. Split each string into an array and merge into one array and then use reduce to generate the merged string.

function mergeStrings(a, b) {
    const mergedValues = [
     ...a.split(''),
     ...b.split('')
     ].reduce((values, currentValue) => {
         if (!values.includes(currentValue)) {
             values.push(currentValue);
         }
         return values;
       }, []);

    return Array.from(mergedValues).join('');
}
Emerzonic
  • 21
  • 1
  • 4
  • Please add a more descriptive answer, where you explain why or how this code works. This way the whole community can benefit from your answer. – Sylens Aug 17 '19 at 17:46