10

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.

Richa
  • 4,240
  • 5
  • 33
  • 50

2 Answers2

15

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);
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
6

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)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320