最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Assert if two 2D arrays are equal - Stack Overflow

programmeradmin2浏览0评论

Given two 2D arrays, how can I assert whether or not they are equal?

For example:

array1 = [[1,0],[2,1],[3,0]]
array2 = [[1,0],[2,1],[3,1]]

What is an efficient way to check whether array1 == array2?

Given two 2D arrays, how can I assert whether or not they are equal?

For example:

array1 = [[1,0],[2,1],[3,0]]
array2 = [[1,0],[2,1],[3,1]]

What is an efficient way to check whether array1 == array2?

Share Improve this question asked Nov 24, 2014 at 10:22 IanIan 3,9084 gold badges34 silver badges76 bronze badges 1
  • every value at each index is identical – Ian Commented Nov 24, 2014 at 10:25
Add a ment  | 

3 Answers 3

Reset to default 6

If by equality you mean the array contents have same elements in the same order, then the shortest (though not the fastest) way will be:

JSON.stringify(array1) === JSON.stringify(array2)

This will work with arrays of any dimensions.

UPDATE: If you need a really fast algorithm then simple iteration will work better. However it is less fool-proof, hence to make it really safe and secure you'll need to spend more development time. Here is one possible solution for modern browsers:

function equal(array1, array2) {
    if (!Array.isArray(array1) && !Array.isArray(array2)) {
        return array1 === array2;
    }

    if (array1.length !== array2.length) {
        return false;
    }

    for (var i = 0, len = array1.length; i < len; i++) {
        if (!equal(array1[i], array2[i])) {
            return false;
        }
    }

    return true;
}

The following JSPerf speed test shows the supremacy of this algorithm over the short JSON approach: http://jsperf./2d-array-parion.

The most efficient way would always depend on the size of the array/s and on your application and usage for them. You can check for the lengths of the 2 arrays for an early termination in case of a non match, but this might be considered as an extra step if that case rarely happens.

boolean areEqual(array array1, array array2){
if array1.length != array2.length
    return false;
for (int i=0;i<array1.length; i++)
    if(!areEqual(array1[i], array2[i])
        return false;
return true;
}

boolean areEqual(int first, int second){
    return first == second;
}

The way to go would be to iterate all values in a nested loop, pare value by value. Use a boolean which you set to false at the first mismatch, and assert that this boolean is true in your test.

发布评论

评论列表(0)

  1. 暂无评论