Home > Software engineering >  How can I increment multiple values in a single loop based on conditions
How can I increment multiple values in a single loop based on conditions

Time:09-18

I have an object that holds the totals of some entities where I need to loop through another array of objects which have some boolean properties I want to check and if true then I want to increment the relevant counter in the totals object.

A simple example of what I'm trying to do is below and works fine as is however I was wondering how I can achieve this in a cleaner way possibly with map/filter/reduce etc. but I would still like to only have to loop through the array once and avoid iterating over it multiple times

const totals = { a: 0, b: 0, c: 0 };

myArr.forEach((val) => {
  if (val.condition1) {
    totals.a  ;
  }

  if (val.condition2) {
    totals.b  ;
  }

  if (val.condition3) {
    totals.b  ;
  }
});

CodePudding user response:

Here is a way of checking an array of objects (data) for number of given conditions (defined in array checkFor):

const data=[{cond1:1,cond2:1},{cond1:1,cond3:1},{cond3:1,cond4:1},{cond2:1,cond4:1},{cond3:1,cond4:1},{cond1:1,cond2:1},{cond1:1,cond2:1},{cond5:1,cond7:1},{cond1:1,cond2:1}];

checkFor="cond1,cond2,cond3,cond4".split(",");

const sums=data.reduce((a,o)=>{
 checkFor.forEach(c=>{
  if(o[c]){
   a[c]??=0;
   a[c]  ; 
  }
 })
 return a;
}, {});
console.log(sums);

CodePudding user response:

There are a lot of way to increment more than a variable in a single loop

for (int i = 0; i != 5;   i and   j) 
do_something(i, j);

Or also you can try this:

    int j = 0;
for(int i = 0; i < 5;   i) {
    do_something(i, j);
      j;
}
  • Related