[Easy] difference

January 28, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

Question Prompt

Let's consider a code optimization challenge. We have a function that processes an array of values. However, some of these values might appear in other arrays as well. We want to optimize the function to only process unique elements from the first array. Design a function named difference that efficiently determines these unique elements using SameValueZero comparisons, minimizing unnecessary processing on duplicate values.

difference([], []); // []
difference([1, 1, 2, 3], [2, 3]); // [1, 1]
difference([1, 2, 3], [1, 2, 3, 4]); // []
difference([4, 3, 2, 1], [1, 2, 3]); // [4]

Solutions

Loops through the first array and checks if each element:

  • Isn't included in any subsequent arrays (includes(element) === false).
  • Isn't explicitly undefined.

If both conditions are met, adds the element to the unique elements array.

function difference(array, values) {
  const result = [];
  for (const element of array) {
    if (values.includes(element) === false && element !== undefined) {
      result.push(element);
    }
  }
  return result;
}

Or we can do it more concisely. First, we can create a set for fast lookup. Then filter the first array: Retains only elements that aren't present in the valuesSet, creating a new array with unique elements.

function difference(array, values) {
  const valuesSet = new Set(values);
  return array.filter((value) => !valuesSet.has(value));
}
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee