1

I have an array defined as,

var array = [[
    ["a"],
    ["t"]
], [
    ["b"],
    ["t"]
], [
    ["c"],
    ["t"]
]]

The desired output is :

a t
b t
c t

I have tried with

rows.join("\n")

which give

a,t
b,t
c,t

I have a huge list, which needs the highly efficient code that maps each of the inner arrays instead traditional for, while loops

2
  • can't map an array without using loops. Even Array.prototype methods use loops internally. Where is this output supposed to be used? Commented Jan 4, 2017 at 10:07
  • 1
    Your array seems invalid, double check what you have provided. Commented Jan 4, 2017 at 10:07

3 Answers 3

3

You could use Array#map for the outer array with the line feed and Array#join with ' ' for inner and with '\n' for outer arrays.

var array = [
        [["a"], ["t"]],
        [["b"], ["t"]],
        [["c"], ["t"]]
    ],
    result = array.map(function (a) { 
        return a.join(' ');
    }).join('\n');

console.log(result);

ES6

var array = [
        [["a"], ["t"]],
        [["b"], ["t"]],
        [["c"], ["t"]]
    ],
    result = array.map(a => a.join(' ')).join('\n');

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

Join function does not work for nested array. You can use following way to handle such situation.

var array = [
    [    ["a"],    ["t"]    ], 
    [    ["b"],    ["t"]    ],
    [    ["c"],    ["t"]    ]
    ];

    for (var i=0, l=array.length; i<l; i++){
        if (array[i] instanceof Array){
            array[i] = array[i].join(" ");
        }
    }
    var energy = array.join('\n');

Comments

0

All array methods are fancy but may be you can still simply do like

var arr = [[["a"],["t"]],
           [["b"],["t"]],
           [["c"],["t"]]
          ],
 result = arr.join("\n").replace(/,/g," ");
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.