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 plained 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?
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 plained 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?
2 Answers
Reset to default 4you 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
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:
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.