-1

I have two string arrays (always will contain string values)

var origArr = ['b', 'c', 'a'];
var currentArr = ['d', 'a', 'e', 'c'];

And I need two functions: one that finds what has been added (d, e) and one that finds what has been removed (b). I have a function that finds all the differences, but I cannot figure out how to do this. Also efficiency is important and these arrays might contain over 1000 values and they are not sorted. Lastly, it shouldn't fail if one or both of the arrays is empty.

function getArrayDifference(a1, a2) {
    var tempArr = [],
        diffArr = [];
    for (var i = 0; i < a1.length; i++) {
        tempArr[a1[i]] = true;
    }
    for (var j = 0; j < a2.length; j++) {
        if (tempArr[a2[j]]) delete tempArr[a2[j]];
        else tempArr[a2[j]] = true;
    }
    for (var k in tempArr) {
        diffArr.push(k);
        return diffArr;
    }
}
trueimage
  • 309
  • 2
  • 4
  • 14
  • 2
    Your question doesn't specify exactly what you're having problems with. If you're just looking for someone to write code for you, I recommend looking over [careers.stackoverflow.com](http://careers.stackoverflow.com) to hire a developer. – zzzzBov Apr 02 '14 at 20:02
  • [This may help you](http://stackoverflow.com/questions/1187518/javascript-array-difference). – The Alpha Apr 02 '14 at 20:03
  • I don't know how to do it... if you want to write out the pseudo code I will code it... – trueimage Apr 02 '14 at 20:04

1 Answers1

1

Try this:

function arrayDiffAdded(arr1, arr2) {
    var ret = [];
    for(var i=0, l=arr2.length; i<l; ++i)
        if(!~arr1.indexOf(arr2[i]))
            ret.push(arr2[i]);
    return ret;
}
function arrayDiffRemoved(arr1, arr2) {
    return arrayDiffAdded(arr2, arr1);
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    @trueimage `~` is the [bitwise not operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#.7E_%28Bitwise_NOT%29). `~arr.indexOf(foo)` is a trick that gives a truly number if `arr` contains `foo`, or falsy `0` otherwise. – Oriol Apr 02 '14 at 22:17