使用d3.csv解析CSV时map返回多数组,需保留最后完整数组
Fix: Only Output the Complete Array from D3 CSV Parsing
The problem you're seeing comes from two key issues in your code:
- You're using a global
myArrayto accumulate data, which means if thed3.csvcallback runs multiple times (e.g., due to caching quirks or older D3 behavior), you'll end up with partial datasets being processed and logged each time. - You're logging the result inside the callback every time it executes, so you get multiple outputs instead of just the final complete one.
Here's the fixed code that will only output the full, correct array:
d3.csv("Data.csv", function(data) { // Grab all unique header keys from the full dataset const uniqueKeys = [...new Set(data.flatMap(row => Object.keys(row)))]; // Build your target array format const res = uniqueKeys.map(key => { // Collect values for this key, filtering out null/undefined entries const rowValues = data.map(row => row[key]).filter(val => val != null); return [key, ...rowValues]; }); // Log only the complete result once console.log(res); });
What changed:
- Removed the global
myArray: Thedataparameter passed to thed3.csvcallback is already the full parsed CSV dataset (an array of row objects). You don't need to accumulate it over multiple runs. - Directly use the full dataset: All processing now uses the single
dataarray, so you're only working with complete data. - Single log statement: The result is only logged once, after processing the full dataset.
For modern D3 (v5+), use Promise syntax (recommended):
If you're using a newer version of D3, this Promise-based approach is cleaner and includes error handling:
d3.csv("Data.csv") .then(data => { const uniqueKeys = [...new Set(data.flatMap(row => Object.keys(row)))]; const res = uniqueKeys.map(key => { const rowValues = data.map(row => row[key]).filter(val => val != null); return [key, ...rowValues]; }); console.log(res); }) .catch(error => { console.error("Failed to load CSV:", error); });
This ensures you only process and log the data once it's fully loaded, and you'll catch any issues with file loading too.
内容的提问来源于stack exchange,提问作者House97_
相关产品推荐
相关产品推荐

