Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
How do I count the number of truth values in array?

I am struggling with some logic but I think I am close. Is there any way to get the number of truth values from an array of booleans?

  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//);
      }
    });
  }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The easiest way is with reduce. Here's the example.

const checkedState = [true, false, true]

const answer = checkedState.reduce((acc, val) => val ? acc + val : acc);

console.log(answer)

about 4 years ago · Juan Pablo Isaza Relatório

0

filter out the elements that are true, and return the length of that array.

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

Basically filtering the array and looking for the truthy values and checking the length of the array will do the trick and after that you can call the setCourseProgress(count) with the right count value.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda