最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use Javascript array.find() with two conditions? - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question edited Apr 24, 2020 at 12:06 codemon asked Apr 24, 2020 at 4:36 codemoncodemon 1,6041 gold badge19 silver badges28 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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

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.
发布评论

评论列表(0)

  1. 暂无评论