[英]jquery count multidimensional array by value
请帮助我计算表格中的特定值。
我有一些这种形式的数据:
var data = {
"metadata": ["FZ", "CS", "CU", "CZ"],
"values": [
["CON", "184.0", "null", "null"],
["ERG SRL", "35.0", "null", "57.0"],
["IO", "6.0", "null", "null"],
["IND", "null", "1753.0", "null"],
["LIXL", "1644.0", "null", "3748.0"],
["MOXRL", "2285.0", "null", "0.0"],
["MOLXL", "11.0", "null", "0.0"],
["MURX", "5362.0", "null", "275.0"],
["STRL", "197.0", "null", "39.0"]
]
};
这是jsbin的结果 。 在该表中,我有一些值,如null
, 0.0
和其他。
我只想在键上计算此值:示例:这是我的表:
FZ CS CU CZ CON 184.0 null null ERG 35.0 null 57.0 IO 6.0 null null IND null 1753.0 null LIXL 1644.0 null 3748.0 MOXRL 2285.0 null 0.0 MOLXL 11.0 null 0.0 MURX 5362.0 null 275.0 STRL 197.0 null 39.0
这是我想要的结果:
CS CU CZ all 9 9 9 null 1 8 3 0.0 0 0 2 >0 8 1 4
唯一的结果是当我对生成的表中的单元格进行计数时,但是如果我想进行分页,那么效果不好。
我尝试了.length()
, count++
基于stackoverflow.com上的几个答案,但没有结果。
谢谢大家的提示和回答。
function countValues(values, column, search) {
var total = 0;
for(var i = 0; i < values.length; i++) {
if(values[i][column] === search)
total++;
}
return total;
}
How to use: countValues(data.values, 2, "null")
在您的示例中:
FZ is column 0
CS is column 1
CU is column 2
CZ is column 3
我希望它足够清楚。
但我建议使用AngularJS或下划线之类的框架
这是一个将所有数据映射到创建表的解决方案
HTML:
<table id="counter"></table>
JS:
var tableHeader=['<tr><th></th>'];
/* final mapped object, structured to make html generation and search of metadata vs category easy*/
/* arrays wil contain category count in same array order as metadata*/
var catObj = {'all':[], 'null':[], '0.0':[], '>0':[]};/* ">" used intentionally vs ">" due to html entity*/
/* create header row and populate count arrays with zeros*/
$.each(data.metadata,function(i,item){
tableHeader.push('<th>'+item+'</th>');
$.each(catObj,function(key,arr){
arr[i]=0;
});
});
tableHeader.push('</tr>');
/* categorize the values and update appropriate counter array*/
$.each(data.values,function(i,arr){
$.each(arr, function(idx, val){
catObj[getCategory(val)][idx] ++;
});
});
/* create the table rows from counter arrays*/
var rowsHtml=[];
$.each( catObj,function(key,arr){
rowsHtml.push('<tr><td>'+key+'</td>');
rowsHtml.push( '<td>'+arr.join('</td><td>')+'</td></tr>');
});
/*insert table html*/
$('#counter').html( tableHeader.join('')+rowsHtml.join(''))
/* helper to do categorizing of each value*/
function getCategory(value) {
if (isNaN(value)) {
return value != 'null' ? 'all': 'null';
} else {
return value == 0 ? '0.0' : '>0';
}
}
演示: http : //jsfiddle.net/ykuzg/4
编辑 :
如果需要,可以根据元数据值搜索最终对象,如下所示:
function searchCats( meta, category){
return catObj[category][ $.inArray(meta, data.metadata) ];
}
使用情况
searchCats('FZ', 'all') // returns 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.