简体   繁体   中英

How can I increment multiple values in a single loop based on conditions

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

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

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

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