5

I want to generate an object that will effectively be able to be applied as a patch to array A in order to produce array B.

Given a function isSame which compares two values and returns true if they're the same, or false otherwise (and the purpose of which is to compare two array elements), is there a known algorithm to calculate the difference between two arrays and return a list of specific differences? The differences would be composed of sets of: X elements removed at index Y and the following elements inserted at index Y.

I've written something that sort of works, but it's buggy at the moment and I'm having trouble moving forward with it, and I'm worrying that I'm reinventing the wheel when somebody else may have already done this. http://jsfiddle.net/G6tYt/1/

4
  • possible duplicate of JavaScript based diff utility? Commented Jan 24, 2013 at 12:44
  • No, that's for diffing strings, I believe. Commented Jan 24, 2013 at 13:03
  • No, the algorithm is the same. It works on an array of lines. Commented Jan 24, 2013 at 14:36
  • The difference is the comparison method. I could potentially take the diff algorithm as you suggest, but swap the comparison out for my isSame method...? Commented Jan 24, 2013 at 17:30

1 Answer 1

2

If you want the comparison to be both deep and tolerant of objects and arrays both, then this tool I wrote a while back might be of use:

https://github.com/danski/spahql/blob/master/src/SpahQL.DataHelper.js#L18

SpahQL.DataHelper.compare(
  {"a": "aval", "b": "bval", "c": "cval", "arr": [0,1,2]},
  {"a": "modified", "c": "cval", "d": "added", "arr": [0,1,2,3]}
);
// -> {"/": "~", "/a": "~", "/b": "-", "/d": "+", "/arr": "~", "/arr/3": "+"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.