javascript - 计数除空值外的数组
问题描述
我有一个这样的对象数组:
var a = [{'id': 1}, {'id':''}, {'id':3}]
现在我需要计算除空 id 之外的数组,所以答案应该是 2。我尝试使用过滤器功能,但无法得到预期的输出。
这是我到目前为止完成的代码。
a.filter(Boolean).length; // Returns 3. It should be 2.
任何想法都非常感谢。谢谢
解决方案
// 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)
推荐阅读
- c# - Linq XML 使用属性中的特定值查询父级的后代
- ios - WKWebView 每次应用启动时都会调用 DeviceMotion 和 DeviceOrientation 的请求权限
- python - 用于多项逻辑回归的 Scikit-Learn 与 Keras (Tensorflow)
- sql - 以毫秒为单位的 Hive 字符串到时间戳的转换
- flutter - Dart,在代理模式中以 DRY 或合成方式覆盖许多 getter 和 setter
- ng2-pdfjs-viewer - ng2-pdfjs-viewer 用于提取文本
- amazon-web-services - Glue 以外的 AWS Athena 目录
- google-cloud-platform - 哪些是用于将对象复制到 Cloud Storage 存储分区的凭据
- git - Git 从终端使用正确的用户提交,但不是从 VS Code 提交
- php - È char 保存为 ? 在文件 php