Jump to content

Array of an Array Help


Recommended Posts

I am trying to have a value that looks like this:

let x = [

               ['a','b','c'],

               ['d','e','f'],

               ['g','h','i'],

           ]

and have it show in the console like this:

"abc def ghi"

It seems like an easy solution but I am new to coding and looking for some guidance. Thanks!

Link to post
Share on other sites

The join() method will turn an array into a string with whichever delimiters you like. Since you have nested arrays, you'll have to loop through them and construct string from them. There are multiple ways to do it, here's one:

let x = [
  ['a','b','c'],
  ['d','e','f'],
  ['g','h','i']
];

var out = []; // Temporarily store the internal strings in here.
var item, str; // Variables used in the loop
for(var i = 0; i < x.length; i++) {
  item = x[i]; // Access one of the internal arrays
  str = item.join(""); // Turn the internal array into a string
  out.push(str); // Add the string to the output array
}
var output = out.join(" "); // Turn the output array into an output string
console.log(output);

 

Link to post
Share on other sites

Another approach if the browsers you want to use can handle it:

<script>
let x = [
  ['a','b','c'],
  ['d','e','f'],
  ['g','h','i']
];

console.clear();
console.log('Original: ',JSON.stringify(x));

var xx = x.join(',');
console.log('String: ', xx);

console.log('Stringify: ', ...JSON.stringify(xx));

</script>

 

Link to post
Share on other sites

OK.

 <script>
let x = [
  ['a','b','c'],
  ['d','e','f'],
  ['g','h','i']
];

console.clear();
console.log('Original: ',JSON.stringify(x));

var str = '';
for (var i=0; i<x.length; i++) { str += x[i].join('')+' '; }
console.log(str);

</script> 

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...