admin管理员组文章数量:1415673
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.
本文标签: How to use Javascript arrayfind() with two conditionsStack Overflow
版权声明:本文标题:How to use Javascript array.find() with two conditions? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745240359a2649291.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论