Using arrays as logical sets, or as groups of similar elements, is extremely common and often requires the use of set operations. Unfortunately such operations have not found yet place in the current version of ECMAScript (ES5).
Luckily their implementation requires just a few lines of code, not nearly enough to make it worth creating a library or a module.
If you need to use the operations for more than two arrays the following rules apply:
A ∪ B ∪ C = A ∪ (B ∪ C) = (A ∪ B) ∪ C
A ∩ B ∩ C = A ∩ (B ∩ C) = (A ∩ B) ∩ C
Live demo at: jsfiddle.net/swogger/4gpDB/4/
Often merging two or more arrays into one is required. Unfortunately the native implementation Array.prototype.concat() preserves the duplicate values both arrays have in common, which requires more code to be resolved. Union takes care of that. #####Code:
var fruit = ['apple', 'banana', 'lemon', 'lime', 'pear'];
var sweet = ['icecream', 'banana', 'honey', 'pear', 'sugar', 'apple'];
var result = union(fruit, sweet);
#####Preview:
Fruit Set: apple, banana, lemon, lime, pear
Sweet Set: icecream, banana, honey, pear, sugar, apple
Result Set: apple, banana, lemon, lime, pear, icecream, honey, sugar
#####Code:
var fruit = ['apple', 'banana', 'lemon', 'lime', 'pear'];
var sweet = ['icecream', 'banana', 'honey', 'pear', 'sugar', 'apple'];
var result = difference(fruit, sweet);
#####Preview:
Fruit Set: apple, banana, lemon, lime, pear
Sweet Set: icecream, banana, honey, pear, sugar, apple
Result Set: lemon, lime
#####Code:
var fruit = ['apple', 'banana', 'lemon', 'lime', 'pear'];
var sweet = ['icecream', 'banana', 'honey', 'pear', 'sugar', 'apple'];
var result = intersection(fruit, sweet);
#####Preview:
Fruit Set: apple, banana, lemon, lime, pear
Sweet Set: icecream, banana, honey, pear, sugar, apple
Result Set: apple, banana, pear
#####Code:
var fruit = ['apple', 'banana', 'lemon', 'lime', 'pear'];
var sweet = ['icecream', 'banana', 'honey', 'pear', 'sugar', 'apple'];
var result = exclusion(fruit, sweet);
#####Preview:
Fruit Set: apple, banana, lemon, lime, pear
Sweet Set: icecream, banana, honey, pear, sugar, apple
Result Set: lemon, lime, icecream, honey, sugar
###Thanks for reading! Feedback always welcome.