如何使用Crossfilter对Col2值为0的Col1列数据求和?
Solution to Sum Col1 Where Col2 is 0 in Crossfilter
First off, the issue with your current code is that when d.col2 isn't 0, your callback function doesn't return anything (it implicitly returns undefined). Crossfilter's reduceSum expects a numeric value every time—returning undefined breaks the summation logic entirely.
Here's the fixed version of your code:
var stemTotal = this.ndx.groupAll().reduceSum(function(d) { // Return Col1 value if Col2 is 0, otherwise return 0 to exclude it from the sum return d.Col2 === 0 ? +d.Col1 : 0; });
Key Things to Check:
- Case Sensitivity: Make sure the property names (
Col1andCol2) match exactly with the keys in your data objects. Your original code used lowercasecol1/col2, but your table shows uppercase initials—this mismatch would also cause your code to fail even if the logic was correct. - Explicit Return: By returning
0when the condition isn't met, we ensure the reducer always receives a valid number, so the sum calculates as expected.
To retrieve the final summed value, call:
console.log(stemTotal.value()); // Outputs the total sum of Col1 where Col2 equals 0
内容的提问来源于stack exchange,提问作者BillSut
相关产品推荐
相关产品推荐

