Javascript best practice for finding all the different elements of nested arrays

With two large, potentially very large nested javascript arrays. One is the current, and the other is the previous iteration of this array. The function will have to find all the different elements and act on something changed.

I know how to make a function for this, I wonder what Best Practices is for this. Any good advice would be appreciated. I am considering using either native JavaScript with jQuery, which handles responses to different elements.

This question concerns several things.

  • What is the most effective way to compare objects . In a javascript check, if if, if the object is equal or not equal to another object, it will always say that it is not, even if they are equal. Thus, objects must be broken down and compared.

  • What is the best way to return results? Are you making an array of differences? Walking through the first array, do you clear objects that are the same as in the first, or return a completely new array?

+8
javascript jquery arrays recursion
source share
2 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 consider the second. And change it by removing any common equal values. The array will still be intact, but any values ​​that were the same are now undefined.

+1
source share

Personally, I think recursion is good practice for this situation.

 console.clear(); // Compare 2 nested arrays, do something if values don't match function CompareArrays(arr1, arr2){ for(var i=0;i<arr1.length;i++){ if( typeof arr1[i] === "object"){ // traverse into nested array CompareArrays( arr1[i], arr2[i] ); }else{ if (arr1[i] != arr2[i]){ // do something! console.log( "mismatch @ "+ i +" a1: "+arr1[i]+" a2: "+ arr2[i]); } } } } var a1 = [1,2,3,["a","b","c"],4,5,6,["d","e","f"]]; var a2 = [1,2,55,["a","tt","c"],4,5,6,["d","e","f"]]; CompareArrays( a1, a2); 

working fiddle: http://jsfiddle.net/ymSmP/5

0
source share

All Articles