【问题标题】:How do I count the number of truth values in array? [duplicate]如何计算数组中真值的数量? [复制]
【发布时间】:2021-11-16 05:46:02
【问题描述】:

我正在为一些逻辑而苦苦挣扎,但我认为我已经接近了。有没有办法从布尔数组中获取真值的数量?

  const checkedState = [true, false, true]

  function handleCourseProgress() {
    //for each value that is true in the array...
    checkedState.forEach((value) => {
      //if the value is true...
      if (value === true) {
        //count and total them up here....
        setCourseProgress(//return the count//);
      }
    });
  }

【问题讨论】:

  • Array.reduce() 可能是最简单的方法。
  • 这能回答你的问题吗? Remove all falsy values from an array - 只计算过滤后剩下的内容。
  • 当然可以!不知道用什么方法,谢谢

标签: javascript arrays reactjs foreach boolean


【解决方案1】:

filter 取出 true 的元素,并返回该数组的长度。

const one = [false, true, true];
const two = [true, true, true];
const three = [false, false, false, false];

function trueElements(arr) {
  return arr.filter(b => b).length;
}

console.log(trueElements(one));
console.log(trueElements(two))
console.log(trueElements(three))

【讨论】:

    【解决方案2】:

    const checkedState = [false, true, false, true, true]
    
    const count = checkedState.filter((value) => value).length
    // Cleaner way
    const anotherCount = checkedState.filter(Boolean).length
    
    console.log(count)
    console.log(anotherCount)

    基本上过滤数组并寻找真值并检查数组的长度就可以解决问题,然后您可以使用正确的计数值调用setCourseProgress(count)

    【讨论】:

      【解决方案3】:

      另一种方式是[true, false, true].filter(x=>x).length

      【讨论】:

        【解决方案4】:

        您可以使用简单的filterreduce

        过滤你想要的值,然后计算过滤的长度:

        const filterQuantity = checkedState.filter((x) => x === true).length;
        

        Reduce 将处理每个条目并确定是否需要递增:

        const reduceQuantity = checkedState.reduce((previousValue, currentValue) => {
          return (currentValue) ? previousValue + 1 : previousValue;
        }, 0);
        

        片段:

        const checkedState = [true, false, true];
        
        const filterQuantity = checkedState.filter((x) => x === true).length;
        
        const reduceQuantity = checkedState.reduce((previousValue, currentValue) => {
          return (currentValue) ? previousValue + 1 : previousValue;
        }, 0);
        
        console.info(filterQuantity, reduceQuantity);

        【讨论】:

          【解决方案5】:

          最简单的方法是使用reduce。这是示例。

          const checkedState = [true, false, true]
          
          const answer = checkedState.reduce((acc, val) => val ? acc + val : acc);
          
          console.log(answer)

          【讨论】:

            猜你喜欢
            • 2013-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-21
            • 2019-11-09
            相关资源
            最近更新 更多