benjamine / jsondiffpatch

Diff & patch JavaScript objects
MIT License
4.83k stars 472 forks source link

Array diff when deleting first item #297

Open Benwick91 opened 4 years ago

Benwick91 commented 4 years ago

Hey

I want to use the diff and patch functions for an undo function in my React-Redux project. It works fine, when I am deleting the last item, but not when I deleting the first one or an item inside.

For example I delete the first item:

`{"state":[ {"x": 1, "y": 3}, {"x": 4, "y": 5}, {"x": 2, "y": 6}, {"x": 0, "y": 9} ] }

{"state":[ {"x": 4, "y": 5}, {"x": 2, "y": 6}, {"x": 0, "y": 9} ] }`

The result of diff is:

{
  "state": {
    "0": {
      "x": [
        1,
        4
      ],
      "y": [
        3,
        5
      ]
    },
    "1": {
      "x": [
        4,
        2
      ],
      "y": [
        5,
        6
      ]
    },
    "2": {
      "x": [
        2,
        0
      ],
      "y": [
        6,
        9
      ]
    },
    "_t": "a",
    "_3": [
      {
        "x": 0,
        "y": 9
      },
      0,
      0
    ]
  }
}

But I want to get:

{
  "state": {
    "0": [
      {
        "x": 1,
        "y": 3
      },
      0,
      0
    ]
  }
}

Is this possible? Thank you :)

acouvreur commented 4 years ago

smart array diffing using LCS, IMPORTANT NOTE: to match objects inside an array you must provide an objectHash function (this is how objects are matched, otherwise a dumb match by position is used). For more details, check Array diff documentation

You should provide a hash function, otherwise it based on the position, thus deleting the "first element" only changes the position of the remaining elements. Which will show that the last element is deleted.