0
function difference (arr1, arr2) {
  var combinedArr = arr1.concat(arr2);
  combinedArr = combinedArr.flat();
  var newStr = '';

  for(var i=0; i<combinedArr.length; i++) {
    
  }

  return combinedArr;
}

console.log(difference([1, 2, 3], [100, 2, 1, 10]));
//["1", "2", "3", "10", "100"]

I flattened this array and combined it. Now i'm trying to remove duplicates but I don't know the best way how. I was tinkering with the filter () method and drying to remove like items but I can't figure it out. Any help?

Brixsta
  • 605
  • 12
  • 24

2 Answers2

0

You could use a hash table to store the key-value pairs of element and its existence in the result array

function difference(arr1, arr2) {
  const alreadyHad = {};
  const result = [];
  var combinedArr = arr1.concat(arr2);

  for (const element of combinedArr) {
    if (!alreadyHad[element]) {
      result.push(element);
      alreadyHad[element] = true;
    }
  }

  return result;
}

console.log(difference([1, 2, 3], [100, 2, 1, 10]));

Or simpler, you could use Set

The Set object lets you store unique values of any type, whether primitive values or object references.

function difference(arr1, arr2) {
  return Array.from(new Set([...arr1, ...arr2]));
}

console.log(difference([1, 2, 3], [100, 2, 1, 10]));
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

It would be more easy to understand and maintain with array destructuring and Set.

function difference(arr1, arr2) {
  return [...new Set([...arr1, ...arr2])];
}

// In case you want to sort 
// sort them with Array.prototype.sort method
// array.sort((a, b) => a - b);

console.log(difference([1, 2, 3], [100, 2, 1, 10]));
DecPK
  • 24,537
  • 6
  • 26
  • 42