You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现统计数组对象指定属性中大于0的数值数量?

统计数组对象指定属性中大于0的元素个数

实现思路

定义通用函数接收目标数组与要统计的属性名,通过遍历筛选出指定属性值大于0的元素,返回符合条件的元素数量。

方法一:使用filter(直观易懂)

function countPositiveValues(arr, prop) {
  return arr.filter(obj => obj[prop] > 0).length;
}

方法二:使用reduce(性能更优,避免创建新数组)

function countPositiveValues(arr, prop) {
  return arr.reduce((count, obj) => {
    return obj[prop] > 0 ? count + 1 : count;
  }, 0);
}

示例用法

结合你提供的数组:

let tempObj = [
  {"id":1,"servPrice":0,"bedPrice":0},
  {"id":2,"servPrice":3,"bedPrice":5},
  {"id":3,"servPrice":9,"bedPrice":0}
];

// 统计servPrice大于0的个数
console.log(countPositiveValues(tempObj, 'servPrice')); // 输出:2

// 统计bedPrice大于0的个数
console.log(countPositiveValues(tempObj, 'bedPrice')); // 输出:1

额外说明

如果需要处理属性不存在或属性值非数字的边界情况,可以扩展判断逻辑:

// 扩展版:兼容属性缺失、非数字值场景
function countPositiveValues(arr, prop) {
  return arr.filter(obj => 
    obj.hasOwnProperty(prop) && 
    typeof obj[prop] === 'number' && 
    obj[prop] > 0
  ).length;
}

内容的提问来源于stack exchange,提问作者oguzcan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:00:11