A very simple JavaScript diff function

Tuesday, June 15th 2010, 15:14

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

  • 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.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


CODE EXAMPLES: When you want to include source code or terminal output, please use the the following tags like in the next example:

    [language]
    code lines
    [/language]
	

where you substitute language with the programming laguage used throught the code example (for terminal output that would be bash), e.g:

    [bash]
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    [/bash]
	

To see a list of all the supported languages, please check this page.

If you want to include code bits inline, please use the code tags like in the following example:

    The <code>$USER</code> variable holds the current logged in username.
	

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»

Recent Tweets

Bear