1

I have the following code:

function transposeTwoStrings(arr){
 var stringOne = arr[0];
 var stringTwo = arr[1];

 for (var i = 0; i < arr.length; i++) {
     return (stringOne.charAt(i) + " " + stringTwo.charAt(i));
 }

I am expecting output as follows:

e.g. transposeTwoStrings(['Hello','World']);

should return

H W
e o
l r
l l
o d

However it is only returning the first character at the first index of each string. I am trying to return all characters for both strings.

I initially had a much more verbose solution using if/else and decided to refactor using for loop.

I am stuck as output currently being shown when executed is

H W

0

6 Answers 6

4

You are retuning in the middle of your loop, which will cause it to only loop once. Also, you're using the wrong object to determine the length.

Try this instead:

function transposeTwoStrings(arr){
    var stringOne = arr[0];
    var stringTwo = arr[1];
    var ret = '';

    for (var i = 0; i < arr[0].length; i++) {
        ret += stringOne.charAt(i) + " " + stringTwo.charAt(i) + '\n\r';
    }

    return ret;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I like this based on where mine already is, but when I add the newline it appends it to the last iteration which does not need a newline after
@g01di3l0ck5, You can just change to return ret.trim() or check that i < arr[0].length before appending the \n\r
2

The return in your loop makes it stop during its first iteration. Once you fix that, you should also change the end condition of your loop as otherwise it will only iterate twice.

But you can do it also using split, map and join like this:

function transposeTwoStrings(arr){
    return arr[0].split('')
                 .map( (a, i) => a + ' ' + arr[1][i] )
                 .join('\n'); 
}

var result = transposeTwoStrings(['Hello','World']);

console.log(result);

Alternative with replace callback

function transposeTwoStrings(arr){
    var i = 0;
    return arr[0].replace(/./g, c => c + ' ' + arr[1][i++] + '\n')
}

var result = transposeTwoStrings(['Hello','World']);

console.log(result);

Comments

2

Use one of the strings length as a condition in the for loop:

function transposeTwoStrings(arr){
 var stringOne = arr[0];
 var stringTwo = arr[1];
 var calculatedStr = '';

 var loopCount = 0;

 // CALCULATE LOOP COUNT
 if(stringOne.length > stringTwo.length){
     loopCount = stringTwo.length;
 }else{
     loopCount = stringOne.length;
 }

 for (var i = 0; i < loopCount; i++) {
     calculatedStr += stringOne.charAt(i) + " " + stringTwo.charAt(i));
 }

 // ADD REMAINING CHARACTERS TO STRING RESULT IF SIZE IS DIFFERENT
 if(stringOne.length > loopCount){

     calculatedStr += stringOne.substring(loopCount);

 }
 if(stringTwo.length > loopCount){

     calculatedStr += stringTwo.substring(loopCount);

 }

 return calculatedStr;

}

4 Comments

You'll also want to consider what happens if the strings aren't the same length
That is actually a requirement. for example my tests are (['Hello','World']) (['joey','louise']) (['a','cat']) (['cat','']) (['!a!a!','?b?b'])
@g01di3l0ck5 if the strings are not the same length I suggest you use the smaller of the strings. I edited the answer to show this.
@g01di3l0ck5 I edited the answer to add remaining characters to the result if they were different in size. This should work for all those test cases.
1

this will do the trick:

var strgs = ['Hello','World'];
var res = strgs[0].split('').map((l, ix)=>[l, strgs[1][ix] || '']);
console.log(res);

if you prefer concatenated strings:

var strgs = ['Hello','World'];
var res = strgs[0].split('').map((l, ix)=>l + ' ' + strgs[1][ix] || '')
console.log(res);

printing string to console:

var strgs = ['Hello','World'];
var res = strgs[0].split('').map((l, ix)=>l + ' ' + strgs[1][ix] || '')
res.forEach((e)=>console.log(e));

In case of different size strings the first will define the length and the second element will be '' if the first element don't exist.

Comments

1

You could use the maximal length of the strings and respect empty places.

function transposeTwoStrings(array){
    var i, length = array.reduce(function (r, a) { return Math.max(r, a.length); }, 0),
        result = [];

    for (i = 0; i < length; i++) {
        result.push(array.map(function (a) { return a[i] || ' '; }).join(' '));
    }
    return result;
}

console.log(transposeTwoStrings(['Hello', 'World']).join('\n'));
console.log(transposeTwoStrings(['This', 'is', 'a', 'test']).join('\n'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

Give this a shot:

function transposeTwoStrings(arr) {
  var array = [];
  for (var i = 0; i < arr[0].length; i++) {
    array.push(arr[0][i] + " "+ arr[1][i]);
  }
  return array.join('\n');
}

console.log(transposeTwoStrings(['Hello','World']));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.