Radu Cotescu's professional blog

g33k w17h pa45510n

A Very Simple JavaScript Diff Function

I was faced today with the problem of getting the difference between two JavaScript arrays. After Googling a bit, I haven’t found anything to catch my attention and so I decided to write my own function. It’s not the most efficient way of doing the job and probably not the most elegant either, but it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * Function which returns the result of the subtraction method applied to
 * sets (mathematical concept).
 *
 * @param a Array one
 * @param b Array two
 * @return An array containing the result
 */
function diffArray(a, b) {
  var seen = [], diff = [];
  for ( var i = 0; i < b.length; i++)
      seen[b[i]] = true;
  for ( var i = 0; i < a.length; i++)
      if (!seen[a[i]])
          diff.push(a[i]);
  return diff;
}

I have tested it with Strings and Integers and it worked okay. Use it wisely!

Code

« Oracle TopLink, the ORA-00900 error and stored procedures OpenX Ad Server: Beginner's Guide - review »

Comments