Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
Function is not pulling up the entire array value in typescript

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;
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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', ' ' ];
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!