1

I am trying to get my 2D array to export as a .csv file. My array is in the form: [[1,2],[],[3],[4,5,6]]. I would like the spreadsheet to be formatted as

    h1 h2 h3 h4
    1     3  4
    2        5
             6

I cannot change the format I receive the data in. I've looked into ways to transpose the array but the solutions I've seen don't work with variable size arrays like mine. So far my only idea (in psuedoish code) is:

    for (i < length of longest column; i++) {
         var arr = [];
         if (i > col1.length) arr.push("");
         else arr.push(col1[i]);
         //so on for rest of cols
         csvFile += arr;
    }

Is there a better way to do it?

2 Answers 2

1

You could transpose the array by using arrays with the length of the outer array as length for every line.

var array = [[1, 2], [], [3], [4, 5, 6], [,,7]],
    result = array.reduce((r, a, i, { length }) => {
        a.forEach((v, j) => {
            r[j] = r[j] || new Array(length).fill('');
            r[j][i] = v;
        });
        return r;
    }, []);
    
console.log(result);

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

Comments

1

You are almost there, just missing the inner loop (because a CSV table has rows X columns):

var input = [[1,2],[],[3],[4,5,6]];

var lengthOfLongestColumn = Math.max(...input.map(a => a.length));
var csvFile = [['h1','h2','h3','h4']];

for (var i = 0; i < lengthOfLongestColumn; i++) {
    var row = [];
    
    for (var j = 0; j < input.length; j++) {
        var col = input[j];
        
        if (i >= col.length) {
            row.push('');
        }
        else {
            row.push(col[i]);
        }
    }
    csvFile.push(row);
}

console.log(csvFile)

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.