Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
How to find symmetrical difference using JavaScript?

I've been working on an algorithm that will find the symmetric difference of two arrays (i.e. only items that are in 1 of the 2 arrays, but not both). I've come up with the following so far:

function diffArray(arr1, arr2) {
  let newArr1 = arr1.slice();
  let newArr2 = arr2.slice();
  if (newArr1.length > newArr2.length) {
    return newArr1.filter((item) => !(item in newArr2));
  } else {
    return newArr2.filter((item) => !(item in newArr1));
  }
};

const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);

But when testing with diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) the output is [4, 5] instead of just [4]. The issue seems to happen with whatever the last value of either array is, but I can't seem to figure out what about my code is causing the issue. Thanks in advance for any help.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The in operator checks if the value on the left matches a property name on the right.

In you want to check if one of the property values is in an array, use the includes method.

function diffArray(arr1, arr2) {
  let newArr1 = arr1.slice();
  let newArr2 = arr2.slice();
  if (newArr1.length > newArr2.length) {
    return newArr1.filter((item) => !newArr2.includes(item));
  } else {
    return newArr2.filter((item) => !newArr1.includes(item));
  }
};

const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Updating the answer for another condition

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

function diffArray(arr1, arr2){
  const diff1 = arr1.filter(item => !arr2.includes(item)); // if item not available, the value will be filtered
  const diff2 = arr2.filter(item => !arr1.includes(item));// if item not available, the value will be filtered
  return diff1.concat(diff2);
}
// const result = diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
const result = diffArray([1, 2, 3, 4], [1, 2, 3, 5]); // This condition will fail on the above code
console.log(result);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!