like for eg
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.
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++);
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.
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.