2

I have 3 arrays in Javascript :

var arr1 = [[34.086586, -84.52345500000001], [34.080705, -84.52081499999997], [34.136911, -83.97300999999999], [34.090184, -84.51971000000003], [33.99105, -83.717806]];
var arr2 = [[34.29712, -83.86256700000001]];
var arr3 = [[33.99105, -83.717806]];

How can I check if arr2 or arr3 are inside arr1 ?

Thanks

3
  • 1
    See stackoverflow.com/questions/7837456/… for how to compare two arrays. Then just loop through arr1, comparing the elements to arr2[0] and arr3[0]. Commented Jun 4, 2016 at 10:17
  • Did you understand my question? I don't want to campare arrays, I want to see if the values in arr2 or arr3 are inside arr1. Commented Jun 4, 2016 at 10:22
  • That's what I understood. When you loop through arr1 the elements are arrays like [34.086586, -84.52345500000001]. You compare this to [34.29712, -83.86256700000001] to see if it matches arr2. Commented Jun 4, 2016 at 10:23

1 Answer 1

2

You could iterate over the haystack and the needles and if the length of the arrays inside is equal, check every value.

function check(haystack, needles) {
    return haystack.some(function (h) {
        return needles.some(function (n) {
            return h.length === n.length && h.every(function (a, i) {
                return a === n[i];
            });
        });
    });
}

var arr1 = [[34.086586, -84.52345500000001], [34.080705, -84.52081499999997], [34.136911, -83.97300999999999], [34.090184, -84.51971000000003], [33.99105, -83.717806]],
    arr2 = [[34.29712, -83.86256700000001]],
    arr3 = [[33.99105, -83.717806]];

console.log(check(arr1, arr2));
console.log(check(arr1, arr3));

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

1 Comment

Perfect, thanks, it is better than the compare arrays suggested below.

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.