【问题标题】:Count array except the empty values [duplicate]计数除空值外的数组[重复]
【发布时间】:2021-02-19 04:38:13
【问题描述】:

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

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

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

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

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

非常感谢任何想法。谢谢

【问题讨论】:

  • 你能解释一下a.filter(Boolean).length; 想要做什么吗?
  • 我认为您误解了文档。您不会将文字“布尔”作为filter 的参数。根据您是保留还是排除数组中的每个项目,您传递返回 true 或 false 的内容。通过传递Boolean,您只是为每个元素返回一个非假值,因此它不起作用。试试这个例子来更好地理解过滤器:codepen.io/garethredfern/pen/zBLLYW

标签: javascript


【解决方案1】:

// 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)

【讨论】:

    【解决方案2】:

    尝试使用reduce

    const array = [{'id': 1}, {'id':''}, {'id':3}]
    
    const count = array.reduce((acc, cur) => {
     if (cur.id !== '') {
       acc += 1
     }
     return acc
    }, 0)
    
    console.log(count)

    array.filter(Boolean).length 返回 3,因为如果提供程序返回 true,filter 返回元素,在您的情况下,将对象传递给返回 true 的 Boolean({...}),因此它保留所有元素。

    【讨论】:

      【解决方案3】:
      const length = Object.fromEntries(Object.entries(arr).filter(([_, v]) => v.id != '')).length;
      

      console.log(长度);

      你也可以使用Object.fromEntries绕过不匹配的对象元素

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-14
        • 2013-07-25
        • 2017-06-28
        • 2015-12-01
        • 2022-11-01
        • 1970-01-01
        • 2021-05-30
        • 1970-01-01
        相关资源
        最近更新 更多