I needed to create an algorithm which will (efficiently) take an old array and a new array and give me back the changes between the two (which items added, which removed). It ha
I think the implementation of the diff method is correct, the time complexity of your algorithm is O(n * log(n)) because of the sort methods. If you use arrays, you need to sort them before the comparison and the time complexity of sorting algorithms is at least O(n * log(n)).
If the o and n arrays cannot contain the same value more than once, maybe the use of objects (associative arrays) instead of arrays is a better choice.
Example:
function diff(o, n) {
var a = {}; var r = {};
for (var i in o) {
if (!(i in n)) {
r[i] = 1;
}
}
for (var i in n) {
if (!(i in o)) {
a[i] = 1;
}
}
return {added: a, removed: r};
}
// how to use
var o = {"a":1, "b":1, "ab":1};
var n = {"a":1, "aa":1};
var diffon = diff (o, n);
// display the results
var added = "", removed = "";
for (var i in diffon.added) {
added += i + ", ";
}
for (var i in diffon.removed) {
removed += i + ", ";
}
alert ("added: " + added);
alert ("removed: " + removed);
The time complexity in that case is O(n).
If you need further details about arrays, associative arrays in JavaScript, I suggest you the following link: Array object