6

I need to check if any object in an array of objects has a type: a AND if another has a type: b

I initially did this:

const myObjects = objs.filter(attr => attr.type === 'a' || attr.type === 'b');

But the code review complained that filter will keep going through the entire array, when we just need to know if any single object meets either criteria.

I wanted to use array.find() but this only works for a single condition.

Is there anyway to do this without using a for loop?

0

2 Answers 2

4

you can pass two condition as given below

[7,5,11,6,3,19].find(attr => {
    return (attr > 100 || attr %2===0);
});
6

[7,5,102,6,3,19].find(attr => {
    return (attr > 100 || attr %2===0);
});
102
Sign up to request clarification or add additional context in comments.

Comments

-1

Updated answer:

It's not possible to shortcircuit js's builtin functions that does what you want, so you will have to use some kind of loop:

let a;
let b;
for (const elm of objs) {
  if (!a && elm === 'a') {
    a = elm;
  }
  if (!b && elm === 'b') {
    b = elm;
  }
  const done = a && b;
  if (done) break;
}

Also you should consider if you can record a and b when producing the array if that's possible.


Oiginal answer:

`find` works just like `filter` where it takes a predicate, returns the first element that the predicate returns `true`. If I understood your question correctly, you can just replace the `filter` with `find` and it will return at the first occurance:
const myObject = objs.find(attr => attr.type === 'a' || attr.type === 'b');
Also notice your provided snippet is wrong for what you described: `filter` returns an array but you only wanted one element. so you should add `[0]` to the filter expression if you want to use it.

4 Comments

Won't this stop as soon as it finds an element that has a? meaning it will never look for b if it has found a
@codemon Can you phrase your problem more clearly then? Based on your description I assumed you want the first 'a' or 'b'. Or do you want the first 'a' and the first 'b'?
I want the first 'a' or the first 'b' or both if both exist.
@codemon At that point I think the answer is "no": You will have to write a for loop then, and in my opinion well-written for loops are very readable. See edited answer for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.