简体   繁体   中英

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

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

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>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM