我有一个要按年份分组的数组。例如,我在数组中有6个条目,并想创建一个按年份分组的二维数组,因此每年有2个条目...
[4711.067999999985, 12596.399999999936, 12596.399999999936, "Accessories", "2011"]
[5277939.947800145, 8912342.140000183, 8912342.140000183, "Bikes", "2011"]
[16185.937500000333, 42468.34000000009, 42468.34000000009, "Accessories", "2012"]
[11725882.954398958, 19702448.459998813, 19702448.459998813, "Bikes", "2012"]
[168010.80079996982, 448815.8899998886, 448815.8899998886, "Accessories", "2013"]
[14915767.767399808, 24907912.949997608, 24907912.949997608, "Bikes", "2013"]
我希望这是一个类似于...的数组
Array[0][0] = [4711.067999999985, 12596.399999999936, 12596.399999999936, "Accessories", "2011"]
Array[0][1] = [5277939.947800145, 8912342.140000183, 8912342.140000183, "Bikes", "2011"]
Array[1][0] = [16185.937500000333, 42468.34000000009, 42468.34000000009, "Accessories", "2012"]
所以Array[0]
是2011
,Array[1]
是2012
,Array[2]
是2013,等等。
有什么想法如何遍历数组然后按年份分组吗?
答案 0 :(得分:1)
我建议使用JSON格式保存您的数据(将JavaScript作为对象可以很好地工作)。看起来像这样:
{
"years": [
{
"id": 2011,
"value01": 4711.067999999985,
"value02": 12596.399999999936,
"value03": 12596.399999999936,
"type": "Accessories"
},
{
"year": 2012,
...
}
]
}
否则,您仅可以将每个值组合保存为一个字符串,这不是以后使用的最佳解决方案。您可以在w3schools上找到更多信息。
答案 1 :(得分:0)
let data = [
[4711.067999999985, 12596.399999999936, 12596.399999999936, "Accessories", "2011"],
[5277939.947800145, 8912342.140000183, 8912342.140000183, "Bikes", "2011"],
[16185.937500000333, 42468.34000000009, 42468.34000000009, "Accessories", "2012"],
[11725882.954398958, 19702448.459998813, 19702448.459998813, "Bikes", "2012"],
[168010.80079996982, 448815.8899998886, 448815.8899998886, "Accessories", "2013"],
[14915767.767399808, 24907912.949997608, 24907912.949997608, "Bikes", "2013"]
]
yearsList= ['2011', '2012', '2013']
groupByYear = {}
yearsList.map((year, index) => {
groupByYear[index] = [];
data.map(item => {
if(item.includes(year)){
groupByYear[index].push(item)
}
})
})
console.log("groupBy Year", groupByYear, "\n**********END\n\n")
// If you want in 2D array then
let output = Object.values(groupByYear)
console.log("Year 2011 data", output[0]);
console.log("Year 2012 data", output[1]);
console.log("Year 2013 data",output[2]);
答案 2 :(得分:-1)
您可以使用哈希表在O(n)中解决该问题:
const results = [], hash = {};
for(const [v1, v2, v3, category, year] of input) {
if(!hash[year]) {
results.push(hash[year] = []);
}
hash[year].push([v1, v2, v3, category, year]);
}