首页 > 解决方案 > 计数除空值外的数组

问题描述

我有一个这样的对象数组:

 var a = [{'id': 1}, {'id':''}, {'id':3}]

现在我需要计算除空 id 之外的数组,所以答案应该是 2。我尝试使用过滤器功能,但无法得到预期的输出。

这是我到目前为止完成的代码。

         a.filter(Boolean).length; // Returns 3. It should be 2.

任何想法都非常感谢。谢谢

标签: javascript

解决方案


// Your array
const arr = [{'id': 1}, {'id':''}, {'id':3}]

// Filter returns a new array with elements that match the condition below
const length = arr.filter( element => element.id != "" ).length;

console.log(length)


推荐阅读