I am getting this tslint error:
prefer-for-of Expected a 'for-of' loop instead of a 'for' loop with this simple iteration
code:
function collectItems(options) {
const selected = [];
for (let i = 0; i < options.length; i++) {
const each = options[i];
if (each.selected) {
selected.push(each.label);
}
}
return selected;
}
Can somebody help me to understand and resolve this error? I know there an answer on this question but that's not helping in my situation.
for-of
is much more terse and doesn't require manual iteration. The linter is recommending that you write something like this instead, for the sake of readability:
function collectItems(options) {
const selected = [];
for (const each of options) {
if (each.selected) {
selected.push(each.label);
}
}
return selected;
}
But it would be even better to use reduce
in this situation:
const collectItems = options => options.reduce((selectedLabels, { selected, label }) => {
if (selected) selectedLabels.push(label)
return selectedLabels;
}, []);
(You could also use filter
followed by map
, but that requires iterating over the array twice instead of once)
You can use for-of
which iterates over the elements of an array to avoid the ts-lint warning:
function collectItems(options) {
const selected = [];
for (const each of options) {
if (each.selected) {
selected.push(each.label);
}
}
return selected;
}
Or you can use a one liner to filter the array:
const selected = options.filter(e=> e.selected).map(e=> e.label);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With