Mike
Mike

Reputation: 419

Loop thru array to make sure criteria is met on every item

I have an array of items. I want to make sure every item meets a certain criteria.

I wrote this for loop but I'm not sure if it's the most efficient. Is there a better way to do this?

let match = 0;

for (var i = 0; i < lastPressed.length; i++) {
  if (lastPressed[i].o.length === 1 && lastPressed[i].n.length === 0) {
    match++;
  } else {
    break;
  }
}

if(match === lastPressed.length) return true;

return false;

Upvotes: 1

Views: 147

Answers (3)

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

Using builtin every is the best choice here.

However, assuming you want to do it by yourself (for fun, for learning), notice that you don't have to check every item in the array. It's because the very first item that doesn't match the criteria should fail the whole process.

You just have to reverse the condition then. You don't need the count.

for (var i = 0; i < lastPressed.length; i++) {
  if (!(lastPressed[i].o.length === 1 && lastPressed[i].n.length === 0)) {
    return false;
  } 
}

return true;

It's exactly your code but the loop terminates when you find the first nonmatching element.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386883

You could take a for ... of statement and exit early.

This approach uses a destructuring assignment and a negated condition for the check.

for (const { o, n } of lastPressed) {
    if (o.length !== 1 || n.length !== 0) return false;
}
return true;

Upvotes: 0

Aplet123
Aplet123

Reputation: 35560

Javascript has a function just for this: Array.prototype.every.

return lastPressed.every(v => v.o.length === 1 && v.n.length === 0);

Upvotes: 6

Related Questions