You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 myArray to accumulate data, which means if the d3.csv callback 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:

  1. Removed the global myArray: The data parameter passed to the d3.csv callback is already the full parsed CSV dataset (an array of row objects). You don't need to accumulate it over multiple runs.
  2. Directly use the full dataset: All processing now uses the single data array, so you're only working with complete data.
  3. Single log statement: The result is only logged once, after processing the full dataset.

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_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:27:48