AN_05 Posted April 28, 2020 Share Posted April 28, 2020 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 More sharing options...
Ingolme Posted April 29, 2020 Share Posted April 29, 2020 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 More sharing options...
JMRKER Posted April 30, 2020 Share Posted April 30, 2020 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 More sharing options...
Ingolme Posted April 30, 2020 Share Posted April 30, 2020 That doesn't format the array with spaces between each of the internal arrays. Link to comment Share on other sites More sharing options...
JMRKER Posted May 1, 2020 Share Posted May 1, 2020 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now