skip to Main Content

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


  1. Assuming valid JavaScript:

    let arr=[['abc',1],['def',2]];
    

    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:

    console.log(arr.map(a => a[0]).join(''));
    
    Login or Signup to reply.
  2. 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();

    Login or Signup to reply.
  3. You can use Array.prototype.reduce() to join the elements in one iteration:

    const arr = [["abc", 1], ["def", 2]];
    
    const result = arr.reduce((str, [first]) => `${str}${first}`, "");
    
    console.log(result); // "abcdef"
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search