【发布时间】:2018-09-21 16:30:17
【问题描述】:
我有大约数百万条记录的 json 数据。我必须做一个简单但棘手的功能。
我必须做什么?
我必须从该 json 中收集前 10 个出现次数最多的项目及其计数。大多数出现,我的意思是json中项目的最多计数。我还不确定,我将如何使用计数,我的意思是我可以将它添加到与属性相同的 json 对象中。
这是我到目前为止所做的。
//my origional json, it's too big but adding some portion of it.
var jsonData = [
{
"id": "5",
"name": "#5"
},
{
"id": "1",
"name": "#1"
},
{
"id": "2",
"name": "#2"
},
{
"id": "8",
"name": "#8"
},
{
"id": "1",
"name": "#1"
},
{
"id": "10",
"name": "#10"
},
{
"id": "2",
"name": "#2"
}];
var top10Data = [];
//geting top 10 items
function getTop10Data() {
var i = 0;
while (i <= 20) {
top10Data.push(getTop1Data());
i++;
}
return true;
}
//getting top 1 data that has max count in json
function getTop1Data() {
var store = jsonData, distribution = {}, max = 0, result = [];
store.forEach(function (a) {
distribution[a] = (distribution[a] || 0) + 1;
if (distribution[a] > max) {
max = distribution[a];
result = [a];
return;
}
if (distribution[a] === max) {
result.push(a);
}
});
//remove this item with it's all occurences, and push it to top10Data
removeData(result);
return result;
}
//remove items from origional json. but this is not working properly as it removes only one item from top
function removeData(result) {
var length = jsonData.length;
for (var i = 0; i < length; i++) {
if (jsonData[i].toppings === result[0].toppings) {
jsonData.splice(jsonData[i], 1);
}
}
}
我的问题。
我觉得我走的路不合适,有没有更好的方法来处理这种情况。如果我的方法没问题,我在当前代码中缺少什么。
任何帮助将不胜感激。
【问题讨论】:
-
您能否发布您正在处理的实际输入以及所需的输出?
-
实际输入太大而无法包含。我可以添加其中的一部分。
-
嘿,你为什么使用函数只是为了创建一个子数组..你可以很容易地使用“array.slice”..
-
谢谢,你能举一个你想要的输出的例子吗?你想要一个最常见元素的数组,没有重复,还是什么?
-
@PranbirSarkar 好吧,我虽然它会使其易于操作。
标签: javascript jquery sorting optimization