tslint: prefer-for-of Expected a 'for-of' loop instead of a 'for' loop
Asked Answered
C

2

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.

Chiquita answered 12/6, 2018 at 6:22 Comment(1)
Why is the other question not helping?Rubio
G
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);
Gigantes answered 12/6, 2018 at 6:25 Comment(0)
R
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)

Radiometeorograph answered 12/6, 2018 at 6:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.