redline
LowPerformancelookup-in-loop

Array scan inside a loop

Array scan inside a loop. users.find() scans the whole array on every pass of the loop. Build a Set or Map once before the loop.

This is how the comment reads inline, under the flagged line.

Why it matters

.find or .includes inside a loop scans the array once per item: O(n²). Unnoticeable at 50 items, a freeze at 50,000.

What to do

Build a Set or Map once before the loop and look up in O(1).

Examples

Flagged
for (const o of orders) {
  const u = users.find((u) => u.id === o.userId);
}
Better
const byId = new Map(users.map((u) => [u.id, u]));
for (const o of orders) {
  const u = byId.get(o.userId);
}

What it catches

It reads the shape of the code: functions, blocks, loops and calls. Languages: TypeScript and JavaScript. Scope: All files. These cases are the rule's own tests: the first set must be flagged and the second must not.

Flagged

for (const o of orders) {
  const u = users.find((u) => u.id === o.userId);
}

Left alone

const byId = new Map();
for (const o of orders) {
  const u = byId.get(o.userId);
}

Research

`.find`, `.includes` or `.indexOf` inside a loop. It scans the array once per item, which is quadratic work.

  • skill: improve
  • owner's notes

Turn it off or change it

In a config file for the CLI, or in the API's rules field:

{
  "rules": {
    "disable": [
      "lookup-in-loop"
    ],
    "severity": {
      "lookup-in-loop": "medium"
    }
  }
}

Read the source or report a false positive.