我有一组数据,我已经从JSON文件解析了我已经减少到出现次数。我现在需要对从大多数事件发生到最少发生的事件数进行排序。举个例子:
var myData = [{
"datapoint1": "55",
"datapoint2": "500",
"datapoint3": "mydata@data.com",
"datapoint4": 5656
}, {
"datapoint1": "55",
"datapoint2": "404",
"datapoint3": "mydata2@data.com",
"datapoint4": 5656
}, {
"datapoint1": "55",
"datapoint2": "502",
"datapoint3": "mydata3@data.com",
"datapoint4": 5656324
}, {
"datapoint1": "55",
"datapoint2": "500",
"datapoint3": "mydata33@data.com",
"datapoint4": 5656554
}
]
然后我采用了JSON并进行了解析,映射,然后减少到每个数据点2次出现的次数。为简洁起见,上面的虚拟数据重复5-6千次。
var dataParsed = JSON.parse(myData);
var mapDataPoint2 = dataParsed.map(function (data) {
return data.datapoint2
});
var reduceDatapoint2 = mapDataPoint2.reduce(function (prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
console.log(reduceDatapoint2)
此时我可以将输出到控制台记录每次出现的次数。我现在需要能够从大多数到最小的分类。我试过.sort()和 似乎无法做任何事情,在控制台中没有错误。
任何帮助将不胜感激。
答案 0 :(得分:1)
您可以使用reduceDatapoint2
中的值进行排序:
myData.sort((a,b) => reduceDatapoint2[b.datapoint2] - reduceDatapoint2[a.datapoint2]);
样本
var myData = [{
"datapoint1": "55",
"datapoint2": "500",
"datapoint3": "mydata@data.com",
"datapoint4": 5656
},
{
"datapoint1": "55",
"datapoint2": "404",
"datapoint3": "mydata2@data.com",
"datapoint4": 5656
},
{
"datapoint1": "55",
"datapoint2": "502",
"datapoint3": "mydata3@data.com",
"datapoint4": 5656324
},
{
"datapoint1": "55",
"datapoint2": "500",
"datapoint3": "mydata33@data.com",
"datapoint4": 5656554
}
]
var dataParsed = myData;
var mapDataPoint2 = dataParsed.map(function(data) {
return data.datapoint2
});
var reduceDatapoint2 = mapDataPoint2.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
console.log(reduceDatapoint2)
myData.sort((a, b) => reduceDatapoint2[b.datapoint2] - reduceDatapoint2[a.datapoint2]);
console.log(myData);