pkdkk
pkdkk

Reputation: 3961

Javascript, check if array in is another array list

I have an array with som arrays ...

Now I want to check if an array already exists in the array... is that posible?..

arr1 = [0, 0];
arr2 = [[0, 0], [0, 1]]

console.log($.inArray(arr1, arr2));

return : -1

Upvotes: 2

Views: 1157

Answers (4)

user2437417
user2437417

Reputation:

Of course it's possible. Only question is what approach you want to take.

Here's an approach that handles more complex arrays.

function arrayInArray(arr, arrs) {
    return arrs.some(function (curr) {
        return curr.length === arr.length &&
               curr.every(function (_, i) {
                   return curr[i] === arr[i]
               })
    })
}

This makes sure there's an equal number of items in the matching Array, and that the items appear in the same order as the original.

DEMO: http://jsfiddle.net/KEKcX/

console.log(arrayInArray([0,0], arr2)); // true
console.log(arrayInArray([0,1], arr2)); // true
console.log(arrayInArray([1,0], arr2)); // false

Upvotes: 2

Zsolt
Zsolt

Reputation: 3283

What about using JSON.stringify when doing comparison?

function contains (obj1, obj2) {
   for (key in obj1)
      if (JSON.stringify(obj1[key]) == JSON.stringify(obj2))
          return true;
   return false;
}

contains([[0,1], [0,0,1]], [0,1])           // => true
contains({foo: [0,1], bar: [0,0,1]}, [0,1]) // => true

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135792

Here's a generic function that will loop trough the arrays.

function arrayContains(big, small) {
    for (var i = 0; i < big.length; i++) {
        if (big[i].length === small.length) {
            var j = 0;
            while (j < small.length && small[j] === big[i][j]) j++;
            if (j === small.length) return true;
        }
    }
    return false;
}

Usage:

arr1 = [0, 0];
arr2 = [[0, 0], [0, 1]];

console.log(arrayContains(arr2, arr1)); // true
console.log(arrayContains(arr2, [0, 1])); // true
console.log(arrayContains(arr2, [0, 0, 0])); // false
console.log(arrayContains(arr2, [1, 0])); // false
console.log(arrayContains(arr2, [1, 1])); // false

Upvotes: 1

elclanrs
elclanrs

Reputation: 94121

inArray won't do because they're two different objects even if they contain the same values so:

console.log([0,0] == [0,0]); //=> false, they're different objects

You'd have to loop and check if the values match:

var has = false;
for (var i=0; i<arr2.length; i++) {
  if (arr2[i][0] === arr1[0] && arr2[i][1] === arr1[1]) {
    has = true;
    break;
  }
}

Upvotes: 3

Related Questions