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

207
Views
Code refactor with functions in JavaScript

I'm trying to refactor JS code into functions. I'm comparing two arrays and return a new array with any items only found in one of the two given arrays, but not both.

The code below works, but obviously it's not DRY principal.

function diffArray(arr1, arr2) {
  let newArr = []
  for(let el2 of arr2) {
    if(!arr1.includes(el2)) {
      newArr.push(el2)
    }
  }
  for(let el1 of arr1) {
    if(!arr2.includes(el1)) {
      newArr.push(el1)
    }
  }
  return newArr;
}

I want to turn the loop block into a function and below is what i came up with. However, it returns an empty array. What's the issue here?

let newArr = []

function singleEl(arrA, arrB) {
  for(let el of arrA) {
    if(!arrB.includes(el)) {
      newArr.push(el)
    }
  return newArr
}}

function diffArray(arr1, arr2) {
  singleEl(arr2, arr1)
  singleEl(arr1, arr2)
  return newArr;
}

  diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4])
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your problem is return newArr inside the loop.

function singleEl(arrA, arrB) {
  let newArr = [];
  for (let el of arrA) {
    if (!arrB.includes(el))
      newArr.push(el);
  }
  return newArr;
}

function diffArray(arr1, arr2) {
  let result = [];
  result = [...singleEl(arr1, arr2), ...singleEl(arr2, arr1)];

  return result;
}

console.log(diffArray([1, 2], [1, 5, 6]));
console.log(diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]));

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!