mattphillips / deep-object-diff

Deep diffs two objects, including nested structures of arrays and objects, and returns the difference. ❄️
https://www.npmjs.com/package/deep-object-diff
MIT License
1.05k stars 89 forks source link

Array Comparison #6

Closed nahtnam closed 7 years ago

nahtnam commented 7 years ago

Hey,

If you diff two arrays that have some values, but are in a different order, i.e: [1, 3, 2], and [1, 2, 3] the result will be something like: updated position 2 and 3 instead of no change. Is this expected behavior? If so, is there any way I can implement the array to either be sorted or use something like Array.includes()?

nahtnam commented 7 years ago

As an update (for anyone looking), I was able to sort the arrays myself with this:

(json) => {
  let sortedJSON = {}
  sortedJSON = JSON.parse(JSON.stringify(json), (key, value) => {
    if(Array.isArray(value)) {
      return value.sort()
    } else {
      return value
    }
  })

  return sortedJSON
}
mattphillips commented 7 years ago

Hi @nahtnam the output is the correct behaviour. When comparing an array of:

diff([1, 3, 2], [1, 2, 3]) // outputs: { 1: 2, 2: 3 }

The difference is that index 1 has updated to 2and index 2 has updated to 3.

If you wanted these two arrays to be treated as identical (no difference) then sorting each is the right way to go about it before running them through a diff function.

nahtnam commented 7 years ago

Thanks for the reply. Sorting solves 99% of the cases for me so its good enough, but one problem I see is this. If the left array has 5 elements (sorted) and the right has only 4 elements out of the 5 (sorted), then everything after the missing one will be marked as either edited or removed. This kind of problem can only be solved with the diffing algorithm.

Thanks.

mattphillips commented 7 years ago

You are correct that removing a value from an array will result in the difference being considered updated or delete. This is the correct behaviour as the two arrays are not the same and differ at the subsequent indexes of the array. I.e.

// removing the last index of an array then comparing
detailedDiff([1, 2, 3], [1, 2]) 
// returns: { added: {}, updated: {}, deleted: { 2: undefined } }

// removing the middle index of an array then comparing
detailedDiff([1, 2, 3], [1, 3]) 
// returns: { added: {}, updated: { 1: 3 }, deleted: { 2: undefined } }
nahtnam commented 7 years ago

I see, nothing I can really do about a missing element in an array then. Anyways, thank you! I am using your package in https://www.npmjs.com/package/json-diff-cli.