HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Diff Two Arrays - return the symmetric difference of the two arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
symmetricarraysthereturndifferencetwodiff

Problem

This is my challenge using JavaScript -> 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.

My code works, but I think that it can be better.

function diffArray(arr1, arr2) {
 var newArr = [];

  arr1.map(function(val){
   arr2.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  arr2.map(function(val){
   arr1.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  return newArr;
}

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


What do you think?

Solution

As for performance: Array.indexOf in the worse case(element is not there), will have to check all values of the array to check if the value is in it. And doing this for all values of the second array, means O(n m) where n is the arr1 size and m is the arr2 size. If n = m, we can consider that it takes O(nn), which is quite expensive. You could improve this by sorting both arrays and doing a smarter check, but even that will have the cost of the sorting, which is O(n * log n) with a good implementation

Having said all that, what you really want is a structure to check if you have seen or not an element that can check it really quick. In javascript, we can use objets to do this. As its native code we don´t really know the complexity of access, but with testing a bit it is clear that it´s much better (in theory access should be O(1) or O(log n))

The pseudo code is like this:

var seen = {}
iterate all map1 values and mark is as seen
iterate all map2 values and unmark if already seen, mark if not
add all seen values to new array
return array


And here is a full fiddle:



`function diffArray(arr1, arr2) {
var newArr = [];

arr1.map(function(val) {
arr2.indexOf(val)

Code Snippets

var seen = {}
iterate all map1 values and mark is as seen
iterate all map2 values and unmark if already seen, mark if not
add all seen values to new array
return array

Context

StackExchange Code Review Q#124825, answer score: 4

Revisions (0)

No revisions yet.