JSFiddle - React, Tailwind, and code Playground

by chandings

HTML

<a href="" id="a"></a>
<button onclick="download('myfilename.csv', 'text/plain')">Create file</button>

JavaScript

/*	function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}*/


// Function to download data to a file
function download(filename, type) {
		var data = [["col1", "col2", "col3", "col4"], ["row1", "row1", "row1", "row1"], ["row2", "row2", "row2", "row2"], ["row3", "row3", "row3", "row3"], ["row4", "row4", "row4", "row4"], ["row5", "row5", "row5", "row5"]]
    var text = "";
    var row;
    for(var outerIndex = 0; outerIndex< data.length; outerIndex++){
    	row = data[outerIndex];
      for(var innerIndex = 0; innerIndex< row.length; innerIndex++){
      	text+=row[innerIndex]+",";
      }
      	text+="\r";
    }
    console.log(text);
    var file = new Blob([text], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}