0

Newbie here so please excuse the ignorance. I wanted to know why my resulting variable is an empty string, when I loop through the array using forEach and concat method.

const concatSpeakersText = arr => {
    const speakerOneText = ''
    const speakerTwoText = ''

    arr.forEach(utterance => {
        utterance.speaker === '1' ? speakerOneText.concat(' ', utterance.text) : speakerTwoText.concat(' ', utterance.text)
    })

    console.log(speakerOneText)
    console.log(speakerTwoText)
}
4
  • 4
    you never use the result of concat. Commented Mar 10, 2021 at 22:22
  • 4
    Strings are immutable. concat() returns a new string, you need to assign it back to the variable. Commented Mar 10, 2021 at 22:22
  • Duplicate of String Concat not working in scope JS. Read the documentation of concat. This has nothing to do with forEach. You could’ve reduced your minimal reproducible example to let str = ""; str.concat("string"); console.log(str);. Commented Mar 10, 2021 at 22:25
  • Thanks appreciate the resources and feedback Commented Mar 10, 2021 at 22:44

1 Answer 1

1

You need to assign to a variable with String#concat or take an object with the speakers.

const concatSpeakersText = arr => {
    const speakers = { speakerOneText: '', speakerTwoText: '' };

    arr.forEach(utterance => {
        speakers[utterance.speaker === '1'
            ? 'speakerOneText'
            : 'speakerTwoText'
        ] += ' ' + utterance.text;
    });

    console.log(speakers.speakerOneText)
    console.log(speakers.speakerTwoText)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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