Check Whether an Array Exists in an Array of Arrays

Check whether an array exists in an array of arrays?

Because [1,3] !== [1,3], since objects will only equal if they reference the same object. You need to write your own search routine:

function searchForArray(haystack, needle){
var i, j, current;
for(i = 0; i < haystack.length; ++i){
if(needle.length === haystack[i].length){
current = haystack[i];
for(j = 0; j < needle.length && needle[j] === current[j]; ++j);
if(j === needle.length)
return i;
}
}
return -1;
}

var arr = [[1,3],[1,2]];
var n = [1,3];

console.log(searchForArray(arr,n)); // 0

References

  • Using the Equality Operators:

    If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.

How to check if an array exists in List of arrays

Use SequenceEqual:

bool result = Output.Any(a => a.SequenceEqual(coordinates));

How do I check if an array includes a value in JavaScript?

Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

How to check if an array of arrays contains a specific array in scala?

Unless you require raw performance, identified by proper measurements with say jmh, or require Java interop, then try to avoid Array and instead use Scala collections proper such as List:

List(List(1,2), List(2,1)).contains(List(1,2))  // res2: Boolean = true

If you must use Array, then try combination of exists and sameElements like so

test.exists(_.sameElements(Array(1,2)))         // res1: Boolean = true

Why doesn't Array's == function return true for Array(1,2) == Array(1,2)?

How to check if an array contains another array?

Short and easy, stringify the array and compare as strings

function isArrayInArray(arr, item){
var item_as_string = JSON.stringify(item);

var contains = arr.some(function(ele){
return JSON.stringify(ele) === item_as_string;
});
return contains;
}

var myArray = [
[1, 0],
[1, 1],
[1, 3],
[2, 4]
]
var item = [1, 0]

console.log(isArrayInArray(myArray, item)); // Print true if found

check some documentation here

Check if an array contains elements from another array

Your last example is correct if not for forgetting to return the value and moving the if outside.

const winConditions = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
];

const squaresIndices = [0, 4, 8];

const isWin = winConditions.some(
(arr) =>
{
// return if this combination is matching or not
return arr.every(
(square) =>
{
// return if the value matches or not
return squaresIndices.includes(square);
}
);
}
);

// Then test the result
if (isWin)
{
alert("Game Over");
}


Related Topics



Leave a reply



Submit