0

I want to know whether if an array is inside of a 2D array.

This is what I tried:

var x=[1,2];
var y=[[1,1],[1,2],[2,2],[3,3]];

y.includes(x); //should return true
2
  • Even though the 2 arrays look the same...they are not the same array reference. [1,2] !== [1,2] so you can't directly compare them as objects Commented Jan 9, 2017 at 1:50
  • if you wanted to use a library, underscoreJs has _.findIndex(y, x) which would return the position inside y underscorejs.org/#findIndex, or you could make it a truth test with _.findIndex(y,x) >== 0 Commented Jan 9, 2017 at 1:51

2 Answers 2

4

you can create a hash:

var ar = [
    [1,1],[1,2],[2,2],[3,3]
];

var hash = {};
for(var i = 0 ; i < ar.length; i += 1) {
    hash[ar[i]] = i;
}

var val = [1,2];

if(hash.hasOwnProperty(val)) {
    document.write(hash[val]);
}

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

2 Comments

Won't differentiate between ["1", "2"] and [1,2] - not sure if that matters for this case. +1 either way.
Yea if we assume all values in the inner arrays will be integers and not strings then this is great solution!
3

You can do this with chained array methods!

var ar = [
    [1,1],[1,2],[2,2],[3,3]
];

hasDuplicates(ar, [1,"1"]); //false
hasDuplicates(ar, [1,1]); //true

//Use some to determine at least 1 inner array matches
function hasDuplicates(array, valueToCheck) {
    return array.some(function(a, i) {
        //Check each inner arrays index, and verify that it equals on the same index of the array we want to check
        return a.every(function(ax, ix) {
            return valueToCheck[ix] === ax; //triple equals for equality!
        })
    });
}

Demo: https://jsfiddle.net/a3rq70hL/1/

1 Comment

Nice usage of some and every, haven't seen those two in quite a while :)

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.