Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tslint: prefer-for-of Expected a 'for-of' loop instead of a 'for' loop

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.

like image 294
richa_pandey Avatar asked Jun 12 '18 06:06

richa_pandey


2 Answers

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)

like image 171
CertainPerformance Avatar answered Nov 15 '22 15:11

CertainPerformance


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);
like image 42
Titian Cernicova-Dragomir Avatar answered Nov 15 '22 16:11

Titian Cernicova-Dragomir