Reputation: 114
like for e.g.
Array.map((obj, index) => (
condition === true ?
default index counter increment
: do not increase index count
))
I want my counter to increase only if my condition is true, is there any work around for this? I am facing problems when I like adding alternate colors to rows based on object and in case I want to reject certain objects and don't create any rows, even though the row doesn't create, still my counter increases, colors apply on the row which is actually not there and produces UI flaw.
Upvotes: 1
Views: 2171
Reputation: 19080
You could use Array.prototype.forEach() and increment the counter
variable based on the "condition" that is applied to all elements of the array one by one:
let counter = 0;
Array.forEach((o, i) => condition && counter++);
Upvotes: 3
Reputation: 386736
You could use Array#reduce
with a counter, like
var count = array.reduce(function (r, a, i) {
return r + (condition);
}, 0);
instead of Array#map
, because you need a single value and not a new array with all undefined
values.
Upvotes: 2