I have an array that contains a few strings. I want to loop through it and store the result in a variable that I will access as a prop in another component. I want the output to be in the form of individual strings and not return an array. I can use forEach and it returns me the output in the way I want, but we can't return anything in forEach as it is always undefined.
array = ['this', 'is', 'an', 'example']
array.forEach(elem => console.log(elem)) // prints: this
//is
//an
//example
How do I return the individual items of an array like the output shown here and store it in a variable? I tried a traditional for-loop but it returns the first element (I did some digging to find that we can use closures but it didn't solve my issue of storing it in a variable). I feel the solution is simple and I'm needlessly complicating it, any help is greatly appreciated. Thank you.
Edit: My expected output is:
this
is
an
example
I want to receive each item of the array as a separate string and need to store these values in a variable. Sorry for being unclear.
I think you want to join the array with line breaks.
This is how it should work:
let array = ['this', 'is', 'an', 'example']
let result = array.join('\n')
console.log(result);
I'm not sure if I got it, but I'll give you some examples and hopefully, you can use one of them.
var array = ['this', 'is', 'an', 'example'];
console.log(array.join(' ')); //this is an example
console.log(array.toString()); //this,is,an,example
console.log(array.join('')); //thisisanexample
console.log(array.join('-')); //this-is-an-example
I don't know about separate variables, but how about 1 object with separate keys?
let array = ['this', 'is', 'an', 'example'];
const obj = {};
for (let i = 0; i < array.length; i++) {
obj[i] = array[i];
};
array[0]; // this
array[1]; // is