arrays - Trying to solve symmetric difference using Javascript -


i trying figure out solution symmetric difference using javascript accomplishes following objectives:

  • accepts unspecified number of arrays arguments
  • preserves original order of numbers in arrays
  • does not remove duplicates of numbers in single arrays
  • removes duplicates occurring across arrays

thus, example, if input ([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]), solution be, [1, 1, 6, 5, 4].

i trying solve challenge given online coding community. exact instructions of challenge state,

create function takes 2 or more arrays , returns array of symmetric difference of provided arrays.

the mathematical term symmetric difference refers elements in 2 sets in either first or second set, not in both.

although solution below finds numbers unique each array, eliminates numbers occuring more once , not keep order of numbers.

my question close 1 asked @ finding symmetric difference/unique elements in multiple arrays in javascript. however, solution not preserve original order of numbers , not preserve duplicates of unique numbers occurring in single arrays.

function sym(args){     var arr = [];     var result = [];     var units;     var index = {};     for(var in arguments){         units = arguments[i];      for(var j = 0; j < units.length; j++){          arr.push(units[j]);         }     }      arr.foreach(function(a){         if(!index[a]){             index[a] = 0;         }             index[a]++;      });         for(var l in index){            if(index[l] === 1){                result.push(+l);            }        }      return result; } symsym([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]); // => desired answer: [1, 1, 6. 5. 4] 

here's version uses set object make faster lookup. here's basic logic:

  1. it puts each array passed argument separate set object (to faciliate fast lookup).
  2. then, iterates each passed in array , compares other set objects (the ones not made array being iterated).
  3. if item not found in of other sets, added result.

so, starts first array [1, 1, 2, 6]. since 1 not found in either of other arrays, each of first 2 1 values added result. 2 found in second set not added result. 6 not found in either of other 2 sets added result. same process repeats second array [2, 3, 5] 2 , 3 found in other sets, 5 not 5 added result. and, last array, 4 not found in other sets. so, final result [1,1,6,5,4].

the set objects used convenience , performance. 1 use .indexof() them in each array or 1 make own set-like lookup plain object if didn't want rely on set object. there's partial polyfill set object work here in this answer.

function symdiff() {      var sets = [], result = [];      // make copy of arguments array      var args = array.prototype.slice.call(arguments, 0);      // put each array set easy lookup      args.foreach(function(arr) {          sets.push(new set(arr));      });      // see elements in each array unique       // e.g. not contained in other sets      args.foreach(function(array, arrayindex) {          // iterate each item in array          array.foreach(function(item) {              var found = false;              // iterate each set (use plain loop it's easier break)              (var setindex = 0; setindex < sets.length; setindex++) {                  // skip set our own array                  if (setindex !== arrayindex) {                      if (sets[setindex].has(item)) {                          // if set has item                          found = true;                          break;                      }                  }              }              if (!found) {                  result.push(item);              }          });      });      return result;  }    var r = symdiff([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]);  log(r);    function log(x) {      var d = document.createelement("div");      d.textcontent = json.stringify(x);      document.body.appendchild(d);  }

one key part of code how compares given item sets other arrays. iterates through list of set objects, skips set object has same index in array array being iterated. skips set made array it's looking items exist in other arrays. allows retain duplicates occur in 1 array.


here's version uses set object if it's present, inserts teeny replacement if not (so work in more older browsers):

function symdiff() {      var sets = [], result = [], localset;      if (typeof set === "function") {          try {              // test see if constructor supports iterable arg              var temp = new set([1,2,3]);              if (temp.size === 3) {                  localset = set;              }          } catch(e) {}      }      if (!localset) {          // use teeny polyfill set          localset = function(arr) {              this.has = function(item) {                  return arr.indexof(item) !== -1;              }          }      }      // make copy of arguments array      var args = array.prototype.slice.call(arguments, 0);      // put each array set easy lookup      args.foreach(function(arr) {          sets.push(new localset(arr));      });      // see elements in each array unique       // e.g. not contained in other sets      args.foreach(function(array, arrayindex) {          // iterate each item in array          array.foreach(function(item) {              var found = false;              // iterate each set (use plain loop it's easier break)              (var setindex = 0; setindex < sets.length; setindex++) {                  // skip set our own array                  if (setindex !== arrayindex) {                      if (sets[setindex].has(item)) {                          // if set has item                          found = true;                          break;                      }                  }              }              if (!found) {                  result.push(item);              }          });      });      return result;  }      var r = symdiff([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]);  log(r);    function log(x) {      var d = document.createelement("div");      d.textcontent = json.stringify(x);      document.body.appendchild(d);  }


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -