简体   繁体   中英

How do i find the sum of an array with a restriction?

Lets say i wanted to find the sum of all numbers within an array that are equal to or higher than 15. What would the best practice and performance be to solve the issue? The code underneath finds the sum of the whole array.

<script>
    
var list = [15, 5, 5, 5, 15];


// Getting sum of numbers
var sum = list.reduce(function(a, b){
    return a + b;
}, 0);



console.log(sum); // Prints: 25

 </script>

You can use array.filter()

 var list = [15, 5, 5, 5, 15]; // Getting sum of numbers var sum = list.filter(a => a >= 15).reduce((a, b) => a+b); console.log(sum); // Prints 30

 var list = [15, 5, 5, 5, 15]; var sum = list.reduce(function(a, b){ return a + (b >= 15? b: 0); }, 0); console.log(sum);

If you do not want to double loop, you could just use a conditional in the reduce.

You could try:

var cars = [1, 12, 31];
var sum = 0;
for(i = 0; i < 3; i++)
{
    if(cars[i] > 10)
    {
        sum += cars[i]
    }
    
}

you can do forEach

ar list = [15, 5, 5, 5, 15];
var sum = 0;

list.forEach((i) => {
  if (i >= 15) {


    sum += i;
  }
});

console.log(sum)

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