gpt4 book ai didi

javascript - 按列名称过滤 CSV,将具有唯一值(和最大年份字段)的行推送到数组

转载 作者:行者123 更新时间:2023-11-28 06:36:23 25 4
gpt4 key购买 nike

我有一个包含 4 列的 csv:类型、州、年份、值

有多行共享相同的类型和状态。我想过滤 csv,这样我只为每种类型/状态组合获取一行,其中该行包含最近一年的数据。我想知道如何以编程方式执行此操作,因为我的数据文件最终会变得非常非常长。如果可能的话,我想用 JavaScript 来完成此操作。

这是我的数据:

type,state,year,value
oranges,florida,1990,18.17
oranges,florida,1980,14.52
oranges,florida,2000,11.1
oranges,florida,2010,9.8
lemons,florida,1990,8.2
lemons,florida,1980,6.2
lemons,florida,1985,4.1
lemons,florida,1987,5.87
lemons,florida,2002,5.87
lemons,florida,2003,460
lemons,florida,2009,730
lemons,florida,2010,1100
lemons,florida,2011,1200
lemons,florida,2012,1200
lemons,florida,2013,55.5
lemons,florida,2014,55.1
lemons,florida,2015,53.1
limes,florida,1991,49.9
limes,florida,1992,45.6
limes,florida,1993,41.8
limes,florida,2002,3.23
limes,florida,2003,3.23
limes,florida,2009,10.767
limes,florida,2011,34.34492
oranges,california,1964,49.9
oranges,california,1965,0.293
oranges,california,1970,0.293
oranges,california,1990,16
oranges,california,1980,16
oranges,california,1985,29.8
oranges,california,1987,6.3
oranges,california,2002,6.31
oranges,california,2003,6.27
oranges,california,2008,6.24
oranges,california,2009,6.38
oranges,california,2010,10.3
oranges,california,2011,10.3
oranges,california,2012,10.4
oranges,california,2013,8.5
oranges,california,2014,12.6
oranges,california,2015,75.1
lemons,california,1950,74.8
lemons,california,1955,74.5
lemons,california,1960,74.2
lemons,california,1965,72.9
lemons,california,1970,72.7
limes,california,1990,72.4
limes,california,1991,72.1
limes,california,1992,102.56187
limes,california,1993,102.25079
limes,california,1994,96.70884
limes,california,1995,88

我希望我的结果是:

type,state,year,value
lemons,california,1970,72.7
limes,california,1995,88
oranges,california,2015,75.1
lemons,florida,2015,53.1
limes,florida,2011,34.34492
oranges,florida,2010,9.8

最佳答案

  1. 创建空数组
  2. 循环中逐行获取 csv
  3. 用逗号分割即可获取水果的州和年份
  4. 如果数组中不存在水果和状态的组合,则添加到数组中
  5. 否则检查年份,如果较新,则用新值替换数组中的旧值

[编辑]您可以直接在从 csv 转换的数组上循环:

代码示例:

    var items = [];
items['florida_oranges'] = 1990;

//data taken from array list
var newYear = 1994;
var state = 'florida';
var fruit = 'oranges';

//checking
var index = state + "_" + fruit;
if(items[index] && items[index] < newYear) items[index] = newYear;

关于javascript - 按列名称过滤 CSV,将具有唯一值(和最大年份字段)的行推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34246300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com