下面是代码,我用于获取特定groupby
条件的聚合总计数。我最初,使用过滤条件获取所有记录,然后根据groupby
列,我按列获取该组的每个不同值的计数。
allRecords.filter(
function(r){
return r[groupByCondition.column] == groupByCondition.value;
}
).length;
如果groupbyColumn
具有数值,则效果非常好。当按列分组时,它没有得到总计数。
对此有任何帮助将不胜感激。
答案 0 :(得分:0)
使用parseInt
/ parseFloat
将字符串转换为数字
return parseInt(r[groupByCondition.column]) == parseInt(groupByCondition.value);
答案 1 :(得分:0)
问题是groupByCondition.column
而groupByCondition.value
期望groupByCondition = {"column": "col1", "value": "abc"}
这样的对象,但您的问题以groupByCondition = {"col1": "abc"}
的不同方式出现。
您可以更改groupByCondition
对象以适应您以后访问它的方式:
allRecords = [{"col1": "abc", "col2": "xyz"}, {"col1": "cde", "col2": "zxy"}, {"col1": "1", "col2": "bit"}, {"col1": 1, "col2": "byte"}];
function filterRecords(condition) {
result = allRecords.filter(
function(r){
return r[condition.column] == condition.value;
}
);
console.log('The result of filtering by '+JSON.stringify(condition)+' is');
console.log(result);
return result;
}
result = filterRecords({"column": "col1", "value": "abc"});
result = filterRecords({"column": "col1", "value": "cde"});
result = filterRecords({"column": "col1", "value": "1"});
result = filterRecords({"column": "col1", "value": 1});

或者您可以更改访问它的方式以适应条件对象:
allRecords = [{"col1": "abc", "col2": "xyz"}, {"col1": "cde", "col2": "zxy"}, {"col1": "1", "col2": "bit"}, {"col1": 1, "col2": "byte"}];
function filterRecords(condition) {
key = Object.keys(condition)[0];
result = allRecords.filter(
function(r){
return r[key] == condition[key];
}
);
console.log('The result of filtering by '+JSON.stringify(condition)+' is');
console.log(result);
return result;
}
result = filterRecords({"col1": "abc"});
result = filterRecords({"col1": "cde"});
result = filterRecords({"col1": 1});
result = filterRecords({"col1": "1"});

这两个示例都假设您根据仅1列/属性的值过滤记录。如果您想根据多个条件对其进行过滤,则需要额外的工作。