2

i want to check i an array contains the elements of any sub array, i.e. array1 = [10,11,12] array 2 = [[10, 11],[20, 21],[30, 31],[40, 41]];

array1 will be checked in series by each of array2's sub arrays and if the sub array elements are also in the array1 then to return true.

i've tried thing like:

      array2.some((arr) => {
        return arr.every((square) => {
          return array1.includes(square);
        });
      });

or

    for (let elem of array2) {
        if (elem.every((x) => array1.includes(x))) {
          return false;
        } else {
          return true;
        }
      }

any advice would be helpfull. thank you

3
  • What is the problem you are facing? Your snippet one looks okay. In the snippet two, in case of subarray match you are returning false which looks odd. Commented Feb 11, 2022 at 19:35
  • do you want to return true if you have [11, 12] in array2? Commented Feb 11, 2022 at 19:36
  • Are you trying to see if any of the items in array1 exist in a sub-array of array2 or are you trying to see if all of them match a sub-array of array2? Commented Feb 11, 2022 at 20:03

1 Answer 1

2

You need to iterate the sub array as well for the sequence.

const
    array1 = [10, 11, 12],
    array2 = [[10, 11], [20, 21], [30, 31], [40, 41]],
    result = array2.some(a => {
        for (let i = 0, l = array1.length - 1; i < l; i++) {
            if (a.every((v, j) => v === array1[i + j])) return true;
        }
        return false;        
    });

console.log(result);

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

Comments

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.