0

I have some array like this

const array1= ['A', 'B', 'C', 'D'];

const array2= [
{category: 'photos', code: 'A', fileName: '1664725062718.jpg', size: 120306},
{category: 'photos', code: 'F', fileName: '1664725062718.jpg', size: 120306},
{category: 'photos', code: 'K', fileName: '1664725062718.jpg', size: 120306},
];

I need some function that will check if any array member form array1 exist in code property of array2 and return true or false?

Something like this, of course this is just not working example?

array1.some(value => array2.includes(value))
1
  • array1.some(value => array2.find(obj => obj.code === value)) Commented Dec 5, 2022 at 14:45

1 Answer 1

2

I think a clean way is to do the "opposite" and use some on array2, destructuring code from each object, and then checking if the code is in the first array.

const array1= ['A', 'B', 'C', 'D'];

const array2= [
{category: 'photos', code: 'A', fileName: '1664725062718.jpg', size: 120306},
{category: 'photos', code: 'F', fileName: '1664725062718.jpg', size: 120306},
{category: 'photos', code: 'K', fileName: '1664725062718.jpg', size: 120306},
{category: 'photos', code: null, fileName: '1664725062718.jpg', size: 120306},
];

// short-circuiting makes it shorter:
// console.log(array2.some(({ code }) => code && array1.includes(code)));
console.log(array2.some(({ code }) => code ? array1.includes(code) : false));

Sign up to request clarification or add additional context in comments.

4 Comments

This is ok, but what is code is null, it will get error includes does nto accept null?
@MiomirDancevic Check if it is null before using includes then
Please write answer that i can accept, thanks
Probably worth at least noting that an array is a really poor choice of data structure for membership lookups. Array1 should really be an object or a set.

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.