2

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
1
  • 1
    Well, [0,0] != [0,0]. So you'd have to loop and compare. Commented Jun 16, 2013 at 22:08

4 Answers 4

3

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

1

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

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.