Suhan Gui
Suhan Gui

Reputation: 43

Finding if an array is in a 2D array

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

Upvotes: 0

Views: 49

Answers (2)

tymeJV
tymeJV

Reputation: 104775

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/

Upvotes: 3

Yaser
Yaser

Reputation: 5719

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]);
}

Upvotes: 4

Related Questions