Download Javascript Matrix

Download the content of a Matrix into a csv file.

by Karl Tayfer

HTML

<p>Step 1: Download the matrix csv.</p>
<p><button type="button" id="downloadButton">Download</button></p>
<p>Step 2: Upload the csv matrix and check the Javascript console.</p>
<p><input type="file" id="uploadFile" accept=".csv" /></p>

JavaScript

function downloadArray() {
	var matrixExample = [[1, 0], [0, 1]],
    	link = document.createElement('a');
    
    link.setAttribute('download', 'matrix.csv');
    link.setAttribute('href', 'data:text/plain;base64,' + btoa(matrixExample.join('\n')));
    link.click(); 
}

function uploadArray(evt) {
	var file = evt.target.files[0],
    	fileReader = new window.FileReader();
    
    fileReader.readAsText(file);
    fileReader.onload = function (evt) {
        var matrixResult = evt.target.result.split('\n');
        for (i = 0, l = matrixResult.length; i < l; i += 1) {
            matrixResult[i] = matrixResult[i].split(',');
        }
        window.console.log(matrixResult);
    };
}

document.getElementById('downloadButton').addEventListener('click', downloadArray, false);
document.getElementById('uploadFile').addEventListener('change', uploadArray, false);