Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda