Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Best Practice for finding all differing Nested Array Elements

With 2 large, potentially very large nested javascript arrays. One is current and the other is previous iteration of this array. The function will need to find all differing elements and act upon anything changed.

I know how to make a function to do this, I am wondering what the Best Practices are for doing such a thing. Any good advice will be appreciated. I am looking at using either native JavaScript with jQuery handling the responses to the differing elements.

This Question deals with several things.

  1. What is the most efficient way to compare objects. In javascript checking, via if, if a an object equals or does not equal another object, will always say it does not, even if they are equal. Thus the objects need to be broken down and compared.

  2. What is the best way to return the results? Do you make an array of the differences? While going though the first array do you clear out objects that are the same as they are in the first, or make an entirely new array to return?

like image 631
Case Avatar asked May 13 '13 01:05

Case


1 Answers

function CompareArrays(arr1, arr2){    
    for(var key in arr1){
        if( arr1[key] !== arr2[key]){
            // traverse into nested array
            if(typeof(arr1[key]) == 'object' || typeof(arr2[key]) == 'object'){                
                CompareArrays( arr1[key], arr2[key]);
            }
        }else{
                delete arr2[key];
        }
    }
}

var a1 = [1,2,3,["a","b","c"],4,5,6,["d","e","f"]];
var a2 = [1,2,5445,["a","tt","c"],4,5,336,["d","edee","ffdf"], 'blablabla', 'I\'m extra'];

CompareArrays( a1, a2 );
console.log(a2);

This will look at the second given. And modify it removing any shared equal values. The array will still be intact but any values that were the same are now undefined.

like image 114
Billy Avatar answered Nov 14 '22 22:11

Billy