Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Last active January 11, 2020 17:01
Show Gist options
  • Select an option

  • Save martin-mok/a2033648c32417bde31ea05dcca1e702 to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/a2033648c32417bde31ea05dcca1e702 to your computer and use it in GitHub Desktop.
freecodecamp: Diff Two Arrays

Description

Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays. Note:You can return the array with its elements in any order.

Tests

tests:
  - text: <code>diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])</code> should return an array.
    testString: assert(typeof diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) === "object");
  - text: <code>["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]</code> should return <code>["pink wool"]</code>.
    testString: assert.sameMembers(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]), ["pink wool"]);
  - text: <code>["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]</code> should return an array with one item.
    testString: assert(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]).length === 1);
  - text: <code>["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]</code> should return <code>["diorite", "pink wool"]</code>.
    testString: assert.sameMembers(diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]), ["diorite", "pink wool"]);
  - text: <code>["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]</code> should return an array with two items.
    testString: assert(diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]).length === 2);
  - text: <code>["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]</code> should return <code>[]</code>.
    testString: assert.sameMembers(diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]), []);
  - text: <code>["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]</code> should return an empty array.
    testString: assert(diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]).length === 0);
  - text: <code>[1, 2, 3, 5], [1, 2, 3, 4, 5]</code> should return <code>[4]</code>.
    testString: assert.sameMembers(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), [4]);
  - text: <code>[1, 2, 3, 5], [1, 2, 3, 4, 5]</code> should return an array with one item.
    testString: assert(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]).length  === 1);
  - text: <code>[1, "calf", 3, "piglet"], [1, "calf", 3, 4]</code> should return <code>["piglet", 4]</code>.
    testString: assert.sameMembers(diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]), ["piglet", 4]);
  - text: <code>[1, "calf", 3, "piglet"], [1, "calf", 3, 4]</code> should return an array with two items.
    testString: assert(diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]).length === 2);
  - text: <code>[], ["snuffleupagus", "cookie monster", "elmo"]</code> should return <code>["snuffleupagus", "cookie monster", "elmo"]</code>.
    testString: assert.sameMembers(diffArray([], ["snuffleupagus", "cookie monster", "elmo"]), ["snuffleupagus", "cookie monster", "elmo"]);
  - text: <code>[], ["snuffleupagus", "cookie monster", "elmo"]</code> should return an array with three items.
    testString: assert(diffArray([], ["snuffleupagus", "cookie monster", "elmo"]).length === 3);
  - text: <code>[1, "calf", 3, "piglet"], [7, "filly"]</code> should return <code>[1, "calf", 3, "piglet", 7, "filly"]</code>.
    testString: assert.sameMembers(diffArray([1, "calf", 3, "piglet"], [7, "filly"]), [1, "calf", 3, "piglet", 7, "filly"]);
  - text: <code>[1, "calf", 3, "piglet"], [7, "filly"]</code> should return an array with six items.
    testString: assert(diffArray([1, "calf", 3, "piglet"], [7, "filly"]).length === 6);

Solution

My soln:

function diffArray(arr1, arr2) {
  var newArr = [];
  let inCommon = arr1.filter(e=>arr2.indexOf(e)>=0);//get the common items array
  newArr=arr1.filter(e=>inCommon.indexOf(e)<0).concat(arr2.filter(e=>inCommon.indexOf(e)<0));
  return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Offical soln:

function diffArray(arr1, arr2) {
  var newArr = [];
  var h1 = Object.create(null);
  arr1.forEach(function(e) {
    h1[e] = e;
  });

  var h2 = Object.create(null);
  arr2.forEach(function(e) {
    h2[e] = e;
  });

  Object.keys(h1).forEach(function(e) {
     if (!(e in h2)) newArr.push(h1[e]);
  });
  Object.keys(h2).forEach(function(e) {
     if (!(e in h1)) newArr.push(h2[e]);
  });
  // Same, same; but different.
  return newArr;
}

Other solns:
Bonfire Diff Two Arrays

function diff(arr1, arr2) {
  var newArr = arr1.concat(arr2);

  function check(item) {
    if (arr1.indexOf(item) === -1 || arr2.indexOf(item) === -1) {
      return item;
    }
  }

  return newArr.filter(check);
}

Code Explanation:
Merge both arrays on the new one using .concat()
Create a callback function to use with filter. The function will check if the number is not present in both original arrays and return it.
Return the filtered array.
Diff Two Arrays

function diffArray(arr1, arr2) {
 
 arr1Filtered = arr1.filter(function (value){
 return arr2.indexOf(value) === -1;
 });
 
 arr2Filtered = arr2.filter(function (value){
 return arr1.indexOf(value) === -1;
 });
 
 return arr1Filtered.concat(arr2Filtered);
}

Further readings:

How to get the difference between two arrays in JavaScript? - stackoverflow
Comparison of Two arrays Using JavaScript - Sai gowtham
get the Unique elements from the array
Get all unique values in a JavaScript array (remove duplicates)
4 possible solutions:

  1. Use new ES6 feature: [...new Set( [1, 1, 2] )];
  2. Use object { } to prevent duplicates
  3. Use helper array [ ]
  4. Use filter + indexOf
    code using object { } will win because it uses hash.
    Sets in JavaScript - geeksforgeeks

Set implementation javascript

To understand how to implement set data structure. We research how set is implemented in ohter languages.
In python, the diff array problem is solved using set or List Comprehensions.
Python, compute list difference
How is set() implemented?
Indeed, CPython's sets are implemented as something like dictionaries with dummy values (the keys being the members of the set), with some optimization(s) that exploit this lack of values
So basically a set uses a hashtable as its underlying data structure.
Internal working of Set in Python
In Java, Set is implemented by HashSet, LinkedHashSet or TreeSet
Set in Java
Set in C++
What is the underlying data structure of a STL set in C++?
red-black tree is used for ordered set, and hash table is used for unordered set.
Colour it please as Red-Black Trees
Let’s paint the town red (or black)! A simple introduction to Red-Black Trees in Python
Red-Black Tree | Set 1 (Introduction)
Red Black Tree vs AVL Tree

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment