0

How can I combine the output data and make it a string, from a for loop in Javascript.

Here's my snippet.

for (let index = 0; index < routes.length; index++) {
     let element = routes[index];
     meSpeak.speak(element.narrative, speakConfig);
}

It results,

word1
word2
word3
word4

I want to make it as a one String only. like this

word1 word2 word3 word4
6
  • 1
    Why not use routes.join(' ')? Commented Oct 5, 2017 at 5:37
  • it doesn't work Commented Oct 5, 2017 at 5:38
  • share sample data ? or live demo ? what is routes and what does meSpeak.speak() ? Commented Oct 5, 2017 at 5:39
  • routes.forEach(element => meSpeak.speak(element.narrative, speakConfig).join(' '); should work Commented Oct 5, 2017 at 5:41
  • in the routes array, there is a narrative index, i got the data from the routes[index].narrative, and i want to is to make it as a single string Commented Oct 5, 2017 at 5:56

3 Answers 3

1

Just use join()

const routes = [{'narrative':'word 1'},{'narrative':'word2'},
{'narrative':'word 3'},{'narrative':'word 4'}];
let out = []

routes.map((el)=>(out.push(el.narrative)));
res = out.join(' ');

See Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You can try using array. I have sample codes here. Try to implement the logic in your problem

var apples = ["Apple1", "Apple2", "Apple3", "Apple4"];
fruits.toString();

The result will be like:

Apple1,Apple2,Apple3,Apple4

1 Comment

apples != fruits and output should like Apple1 Apple2 not Apple1,Apple2
0

You could add the strings to a variable outside of the for loop and then "speak" the string when the for loop is done.

s = ""
for (let index = 0; index < routes.length; index++) {
     s += str(routes[index].narrative)
}
meSpeak.speak(s, speakConfig);

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.