Home > front end >  I try to write a function that will return the sum of all array elements that are equal to the numbe
I try to write a function that will return the sum of all array elements that are equal to the numbe

Time:10-27

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

CodePudding user response:

An alternative to reduce is to use a simple for/of loop to iterate over the numbers, and then add any found numbers to a sum variable.

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

function sumTheSameNumber(n, arr) {
  let sum = 0;
  for (let i of arr) {
    if (i === n) sum  = i;
  }
  return sum;
}

console.log(sumTheSameNumber(number, array));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related