Jump to content

Array of an Array Help


AN_05
 Share

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 comment
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 comment
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 comment
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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...