Difference between two arrays [Lodash]

by Dawid Ryłko

HTML

<!-- Difference between two arrays [Lodash] -->

<a href="https://dawidrylko.com/nie-pisz-w-kolko-tych-funkcji-wykorzystaj-moc-lodasha/" target="_blank">Różnica pomiędzy dwiema tablicami</a>
<br><br>
<div>JS difference function: <pre id="pureJS">...</pre></div>
<div>Array prototype function: <pre id="prototype">...</pre></div>
<div>Lodash: <pre id="lodash">...</pre></div>

JavaScript

// Difference between two arrays [Lodash]

var array1 = [1, 2, 3, 4, 5];
var array2 = [2, 4, 5];

// JS difference function
function difference(test1, test2) {
  var helpArray = [];
  var difference = [];

  for (var i = 0; i < test1.length; i++) {
    helpArray[test1[i]] = true;
  }

  for (var j = 0; j < test2.length; j++) {
    if (helpArray[test2[j]]) {
      delete helpArray[test2[j]];
    } else {
      helpArray[test2[j]] = true;
    }
  }

  for (var k in helpArray) {
    difference.push(k);
  }

  return difference;
}

// Array prototype function
Array.prototype.difference = function (helpArray) {
  return this.filter(function (i) {
    return helpArray.indexOf(i) < 0;
  });
};

// Lodash
var lodash = _.difference(array1, array2);

console.log(difference(array1, array2)); // ["1", "3"] + in this example "difference"
console.log(array1.difference(array2)); // [1, 3]
console.log(lodash); // [1, 3]

function stringify(obj) {
	return JSON.stringify(obj, null, 4);
}

document.getElementById("pureJS").innerHTML = stringify(difference(array1, array2));
document.getElementById("prototype").innerHTML = stringify(array1.difference(array2));
document.getElementById("lodash").innerHTML = stringify(lodash);