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:
/**
* 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!
You might also like:
1 Comment
Leave a comment
Recent Posts
Projects that I support
Recent Comments
nope said:
yeah that was my first thought too, but: mount: warning: seems to be mounted read-write. too bad, would have been just perfect. more»Klaus Deiss said:
Dear Radu, I tried it on Ubuntu 10.0.4.2 and 10.0.4.3 with different kernel versions (amd64 server 2.6.32 kernel). No... more»scompo said:
Nope.. Now it’s not working again.. This printer it’s a real pain in the butt.. The other hp printer I had... more»Dmitrij said:
Thank you Peter and Patrice. Could you please post the updated script? more»hd_flash_pains said:
didn’t work for me more»








Like it. But I was hoping for something more diff-ish, from the post’s title.
BTW, IMO it’s quite efficient, for what you need – it’s unlikely you can code a more efficient map in Javascript than there is in the native code of the engine.