0

The program has to put all the letters together but it is not working. I've tried with the debugger but does not show any errors. The code:

var phrase = [ 'h', 'e', 'l', 'l', 'o',' ', 'w', 'o', 'r', 'l', 'd' ];

let sentence: string[] = createSentence(phrase);

sentence.forEach(letter => {
    console.log(letter);
});

function createSentence(letters: string[]): string[]
{
    var add = "";
    var result: string[] = [];

    phrase.forEach(unionL => {
        if (unionL != ' ') {
            add += unionL;
        } else {
            result.push(add);
            add = "";
        }
    });

    return result;
}
3
  • What output do you expect? Please specify that too Commented Jun 6, 2022 at 4:02
  • You should return add ? , "result" will always be empty in that code. So update also your function return type to string. Also if you have prop "letters" make use of it instead of the out of scope sentence variable Commented Jun 6, 2022 at 4:02
  • I'm expecting to see "Hello world" Commented Jun 6, 2022 at 4:04

1 Answer 1

2

It's not pulling the entire array because of the condition you have used in your array. You need to add one more condition for the last chunk to be added to the result array. Here is the code:

function createSentence(letters: string[]): string[]

{
    var add = "";
    var result: string[] = [];

    phrase.forEach((unionL,index) => {
        if (unionL != ' ') {
            add += unionL;
        } else {
            result.push(add);
            add = "";
        }
        //New Code
        if(index===phrase.length-1){
            result.push(add);

        }
    });

    return result;
}

Another way is to keep your code and just add an empty string at the end of the string that will work with your logic. Example:

var phrase = [ 'h', 'e', 'l', 'l', ' ', 'w', 'o', 'r', 'l', 'd', ' ' ];
Sign up to request clarification or add additional context in comments.

1 Comment

It worked with the " " at the end, thanks a lot!!!

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.