1

There are many excellent SO & npm solutions for object differences, but I was unable to find one that dealt successfully with a deleted row. The solutions I found would show a deleted row by showing all the following(subsequent) array elements moved up a level.

the original object might look something like this:

[   { id : 1    , 'data' : 'one'               }
,   { id : 22   , 'data' : 'two two'           }
,   { id': 333  , 'data' : 'three three three' }
]

and the new object may look like this:

[   { id : 1     , 'data' : 'one'               }
,   // notice missing "two" data element
,   { id : 333   , 'data' : 'three three three' }
]

I am looking for a solution that resembles how the unix diff works using ordinary text:

 /usr/bin/cat   lhs.txt; 
 {id:1,data:'one'} 
 {id:22,data:'two two'}
 {id:333,data:'three three three'}

 /usr/bin/cat   rhs.txt; 
 {id:1,data:'one'} 
 {id:333,data:'three three three'}

 /usr/bin/diff    lhs.txt    rhs.txt;
 2d1
 < {id:22,data:'two two'}

It would appear that the optimum solution is to look for the missing data element, and splice in an undefined data element for object comparison purposes. I came up with this using underscore pluck and differences:

if  ( lhs.length > rhs.length)    {  
    var lhsKeys     = _.pluck(lhs,"id")     ;
    var rhsKeys     = _.pluck(rhs,"id")     ;
    for ( var id of _.difference(lhsKeys, rhsKeys)  )      {
        rhs.splice((_.pluck(lhs, 'id').indexOf(id)),0,undefined);
                // replace missing array element with an undefined one
    }
}

and now the two objects will be of equal length, so I can compare them with either deep-object-diff or deep-diff

Ideally, there would be an npm module or an underscore function to simply determine the array element row number of the missing element.

Is there a better, shorter, or more efficient solution?

Thank you very much.

edwardsmarkf
  • 1,387
  • 2
  • 16
  • 31
  • JavaScript doesn't have "rows." Do you mean array element? – Jordan Running Mar 02 '17 at 18:23
  • 1
    The unix diff algorithm compares 'lines' and you want to compare 'rows'; that seems like a good fit. A generic diff tool has to account for any kind of data structure. The diff tool doesn't know `id` identifies the row instead of the index. That's why you get such an unoptimized result. Your solution seems fine to me. You could also do deletion detection manually and use the diff to only compare values of records that exist in the input and the output. You could also rebuild your array of rows as an object where each row is identified by the `id`. The diff tool should give a nicer result. – Halcyon Mar 02 '17 at 18:23

0 Answers0