I wonder what is the best way to join items of array into one string. I know that there array.join() for this. And it works perfect for even array of arrays
For ex.
let arr=['a','b','c','d','e','f']
console.log(arr.join(''));
abcdef
but what about
let arr=[['abc',1],['def',2]]
console.log(arr.join(''));
abc,1,def,2
So my question is what is the best way to join only first element of array of arrays mean abc of each element skipping the second element to produce 'abcdef'
string from [['abc',1],['def',2]]
array?
3
Answers
Assuming valid JavaScript:
If you only need the first element of each nested array, you can use
Array.prototype.map
to create a new array which only contains the first elements, then join the new array:you have posted the object, its not an array.
In javascript objects are created using { and }.
For Arrays you can use Array.toString method to convert it to the string with comma separated values.
The Array.toString() method returns a string with all array values separated by commas
const fruits = [["Banana", "Orange1"], ["Apple", "Mango"]];
let text = fruits.toString();
You can use
Array.prototype.reduce()
to join the elements in one iteration: