Home > Mobile >  How to print Array of Arrays on separate lines
How to print Array of Arrays on separate lines

Time:11-25

I have a function which groups anagrams together

function groupAnagrams(strs) {
  let result = {};
  for (let word of strs) {
    let cleansed = word.split("").sort().join("");
    if (result[cleansed]) {
      result[cleansed].push(word);
    } else {
      result[cleansed] = [word];
    }
  }
  console.log(Object.values(result));
  return Object.values(result);
}

it prints the results in the following format

[ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ]

However I would like the output to look like the following

abc, bac, cba

fun, fun, unf

hello

How can I achieve this?

CodePudding user response:

you can do something like this

const data = [ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ]

data.forEach(row => console.log(row.join(', ')))
//or

console.log(data.map(row => row.join(', ')).join('\n'))

CodePudding user response:

Since it's a node.js-tagged question I'll give an example with os.EOL

const { EOL } = require('os');
const lines = [ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ];

const output = lines.map((words) => words.join(', ')).join(EOL);

process.stdout.write(output);

CodePudding user response:

Here's another solutions...

function groupAnagram(arr){
  let res = '';
  arr.map(function(item){
    res  = `${item.join(', ')} \n\n`
  })
  console.log(res)
}

groupAnagram([ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ]
);

CodePudding user response:

Try it:

const arr = [ [ 'abc', 'bac', 'cba' ], [ 'fun', 'fun', 'unf' ], [ 'hello' ] ];

const res = arr.reduce((a, b) => `${a}${b.join(", ")} \n\n`,'');
console.log(res);

  • Related