Design & Download
Your JS Library
in Seconds!!!

Snippet: Set-like Arrays

Written by Christopher West (cwest) on November 14, 2015.
Get the ability to subtract, intersect or union arrays just like you can with sets.
function subtract(array1, array2, opt_matchDups) {
  array1 = slice(array1);
  if (opt_matchDups) {
    array2 = slice(array2);
  }
  for (var e1, i1 = 0, l1 = array1.length, i2, l2 = array2.length; i1 < l1; i1++) {
    e1 = array1[i1];
    for (i2 = 0; i2 < l2; i2++) {
      if (e1 === array2[i2]) {
        l1--;
        array1.splice(i1--, 1);
        if (opt_matchDups) {
          l2--;
          array2.splice(i2--, 1);
        }
        break;
      }
    }
  }
  return array1;
}

function intersect(array1, array2) {
  return subtract(array1, subtract(array1, array2, 1), 1);
}

function union(array1, array2) {
  return array1.concat(subtract(array2, array1, 1));
}

jPaq provided three functions which treated arrays like sets:

Since YourJS is here to replace jPaq, the above snippet basically provides the equivalent of those evil prototypal functions (haha).