Explain Codes LogoExplain Codes Logo

How to export JavaScript array info to csv (on client side)?

javascript
prompt-engineering
performance
feature-detection
Alex KataevbyAlex Kataev·Oct 2, 2024
TLDR

Here's a quick spill-down of exporting a JavaScript array to CSV. We create a Blob from the array, generate a URL with URL.createObjectURL, and then programmatically spark a hidden link to download the file. Here's the sleek code:

const downloadCsv = (filename, array) => { // Detour: escaping reality or just special characters? const csvContent = array.map(row => row.map(field => `"${field.toString().replace(/"/g, '""')}"`).join(",")).join("\n"); // Converting the array content to Blob, sounds blobby? const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); // Don't blink! You might miss creating an object URL const url = URL.createObjectURL(blob); // Does it really link to Narnia? Sadly, No const link = document.createElement('a'); link.href = url; link.download = filename; link.style.display = 'none'; // Say Hi and Bye to the webpage quickly! document.body.appendChild(link); link.click(); document.body.removeChild(link); }; // Example at your service - rock, paper, scissors! downloadCsv('export.csv', [['Header1', 'Header2'], ['Row1Col1', 'Row1Col2']]);

In the jist, this snippet exports any array to a CSV file cleanly, using modern browser capabilities to handle data and trigger the download like a boss!

Delving into the details

The above solution serves the most browsers quite well, but let's dust off the corner cases and explore advanced scenarios.

UTF-8 Charset, our knight in shining armor

When dealing with non-ASCII characters, ensure you specify the charset as UTF-8 to prevent your data from decaying.

Special characters aren't that special here

Fields flowering with special characters or commas need to be enwrapped in double quotes. Double quotes within a field should be escaped by their clones.

A browser's got character

Unlike humans, not all browsers behave the same. A variable approach is necessary:

  • Internet Explorer 11 and its ancestors might fancy msSaveBlob.
  • Firefox, being cheeky, demands the a element to be appended to the DOM; mere creation is not enough!

A fallback isn't always bad

Inculcating feature detection provides fallback options, thereby ensuring your solution has the flairs of compatibility.

Gearing up the code

No one enjoys just functional gear, we seek the performance and advanced detailing. Let's dig in:

forEach, the Rebellious Iteration

How about some punk rock iteration with forEach over your array elements? It boosts readability and champions functional programming.

Feature Detection and Reality Checks

Going beyond feature detection, embrace try...catch blocks or conditional statements to handle different universe versions where Blob might be just a blob of uncertainty.

Saving Special Characters from Extinction

Limiting dealings to various character sets, the UTF-8 setting in the Blob type ensures your special characters don't bid farewell cross-platforming.

Download attribute behaving like a cat

Mind the download attribute's behavior which can be as fickle as a cat across browsers. Notably, Chrome 35 introduced some twists and turns that you might need to ace.

Going bonkers over comprehensive testing

Don't stop at one single browser. Embrace IE 11, Chrome 36, Firefox 29 and others to ensure you have a smooth and universal user experience.