Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!