简体   繁体   中英

Check if array of objects contains value from other array of objects

I have following arrays of objects: 在此处输入图片说明

I need to check if these two arrays have the same begin property. In this case that appears to be true in three objects. So far I have tried this code, but with no luck ( input.value being the first array).

const found = input.value.some((item) => item.begin === filtered.filter((time) => time.begin));

Any ideas how can I achieve this? Thank you in advance.

You could take a Set for the beginnings of filtered and check against the set without more iterations.

Big O of this is O(n), because of O(n) of creating the set and another O(n) of the check and beacause of adding two n you get O(n).

The other approach has because of the nested structure O(n 2 ).

const
    filteredSet = new Set(filtered.map(({ begin }) => begin)),
    found = input.value.some(({ begin }) => filteredSet.has(begin));

您可以使用简单的mapfindIndex方法。

const found = input.value.map((item) => filtered.findIndex((time) => time.begin === item.begin) > -1).findIndex((item) => item === true) > -1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM