简体   繁体   中英

Javascript - Reduce array of arrays

Array input : [["test","test"],["test2","test"],["test2","test2"],["test","test2"]]

Array output : ["test test","test2 test","test2 test2","test test2"]

I'm able to obtain this output with:

output = input.join("|").replace(/,/g," ").toString().split("|")

However, I don't really like this workaround because:

  • It seems unnatural
  • If one of the arrays contains a comma itself, it will be also removed
  • If one of the arrays contains a pipe itself, the split will be not as expected

How can I get the output without those handicaps?

Instead of joining the outer array, you can use map to join each inner array separately:

var arr = [["test","test"],["test2","test"],["test2","test2"],["test","test2"]];
var output = arr.map(subarr => subarr.join(' '));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM