javascript - JavaScript 中 CSV 数据的数据操作(填充、最小、最大)?

标签 javascript algorithm csv data-visualization interpolation

我正在将不同的指标 CSV 文件加载到 JavaScript 中,例如:

CSV for population:

id,year,value
AF,1800,3280000
AF,1820,3280000
AF,1870,4207000
AG,1800,37000
AG,1851,37000
AG,1861,37000

对于每个指标文件,我需要:

  • 填补每个实体缺失的年份 (id)
  • 找出每个实体的时间跨度
  • 找出每个实体的最小值和最大值
  • 找到指标的时间跨度
  • 找到指标的最小值和最大值

执行这些操作的廉价方法是什么?或者,是否有一个很好的 JavaScript 库来执行这些常见的数据操作并将数据有效地存储在各种对象表示中?

我希望上述文件的最终表示类似于:

data = {
    population : {
        entities : 
            AF : {
                data : {
                    1800 : 3280000,
                    1801 : 3280000,
                 },
                entity_meta : {
                    start : 1800,
                    end : 
                    min : 
                    max :
             },
            [...]
        indicator_meta : {
                start : 1700,
                end : 
                min : 
                max :
        }
        [...]

谢谢!

最佳答案

让我们假设您在二维数组中有 CSV 数据:

var data = [[AF,1800,3280000],
[AF,1820,3280000],
[AF,1870,4207000],
[AG,1800,37000],
[AG,1851,37000],
[AG,1861,37000]]

对于这个例子,我将使用 jQuerys 实用函数,因为它会使工作变得容易得多,而且没有任何实际开销。

// we will loop thru all the rows
// if the id does not belong to the entities then we will add the property.
// if the property does exist then we update the values

var entities = {}
$.each(data, function (i, n) {

    // set property
    if (!entities[n[0]]) {
        entities[n[0]] = {
            data : {
                n[1]: n[2]
            },
            entity_meta: {
                start: n[1],
                end: n[1]
                min: n[1]
                max: n[1]
            }
        }

    // update property
    } else {

        // add new data property
        entities[n[0]]['data'][n[1]] = n[2];

        // if the property should change then update it
        if ( entities[n[0]]['entity_meta']['min'] > n[1] ) {
             entities[n[0]]['entity_meta']['min'] = n[1];
        }
    }
});

这显然不是所有代码,但它应该清楚地解释应该采用的方法。

也不是说您预期的最终对象结构非常过于复杂您应该在适当的地方真正使用数组,尤其是对于实体数据

关于javascript - JavaScript 中 CSV 数据的数据操作(填充、最小、最大)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051468/

相关文章:

c# - 如何按递增顺序从数组创建整体列表(子列表)

csv - 如何在 Neo4J 中使用 Cypher 向现有节点添加多个值

javascript - 设置ajax成功回调作为输入值

javascript - 如何在 emberjs 中使用复选框实现多个过滤器?

javascript - OnClick 传递 url 参数

python - 如何使用 Python 删除 CSV 文件的第二行

python - utf-16-le BOM csv 文件

(document).ready() 中的 javascript 函数不执行

javascript - 如何为 Algoexpert.io 的 Non-Constructible Change 挑战设计这种解决方案

java - 优化搜索两个字符串中的关键字