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

195
Visualizações
I try to write a function that will return the sum of all array elements that are equal to the number passed in the array. How can I do it?

this function return the sum of all elements in the array

const array = [4, 7, 24, 7, 0, 10];
const number = 7;

function addTheSameNumbers1(number, array) {
    let count = array.length;
    for (let i = 0; i < count; i++) {
        if (array[i] === number) {
           return array.reduce((a,b) => a + b, 0);
        }
    }
    return null;
}

console.log(addTheSameNumbers1(number, array));```
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Your reduce() is summing all the values. This is how to sum a single number:

const array = [4, 7, 24, 7, 0, 10];
const number = 7;

function addTheSameNumbers1(number, array) {
   return array.reduce((accum, val) =>
     val === number ? accum + val : accum
   , 0);
}

const result = addTheSameNumbers1(number, array);
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understand you correctly, you want to get the sum of the elements that have values which are the same to the length of their parent array. This code should do it.

const filterAndSum = (numbers, query) => {
  return numbers
    .filter((n) => n === query)
    .reduce((n, total) => total + n, 0);
};

console.log(filterAndSum([1,2,3,4,5,4,3,2,1,2,3,2,1], 3))

First, it filters the elements which are not equal to the length of the parent array then gets the sum of the remaining elements. Note that validation is not implemented here, but I believe you could easily do that.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can get the count the occurrence of variable and the multiple with the number

<script>
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
const array = [4, 7, 24, 7, 0, 10];
const number = 7;
var accur = countOccurrences(array, number);
console.log(accur);
console.log(accur * number);
</script>

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