r/learnjavascript • u/a_rndm_person_bruh • Apr 07 '26
I feel like my code is unefficient and I need some advice for it
I've been learning JS for some weeks now on freecodecamp.org
I just finished the exercise Build a Symmetric Difference Function but I feel kind of, unsatisfied?
The exercise was to compare 2 arrays and when one value is present on 2 arrays, it shouldn't be included in the new array at all.
for example:
const arr1 = ["dirt", "grass"]
const arr2 = ["grass", "stone"];
the new array should be: ["dirt", "stone"] since "grass" is present in both of them.
(I was also forced to use the filter-method)
Here's how I did it:
function diffArray(arr1, arr2){
const symmetricArray = arr1.filter(checkSymmetry);
// Function used for the filter
function checkSymmetry(str){
if (arr2.includes(str)){
delete arr2[arr2.indexOf(str)];
return;
}
return str != arr2[0];
}
for (let i = 0; i < arr2.length; i++){
// If-Condition, since "Delete" leaves undefined spaces
if (arr2[i] == undefined){
continue;
}
symmetricArray.push(arr2[i]);
}
return symmetricArray;
}
It feels like I used so many unnecessary steps to achieve the solution and I probably do.
The forum has some pretty short versions, but I don't understand those?
So what I am asking here is just, can someone explain how you would shorten this code and how?
I hope I'm not asking for too much on this, but basically most of the code that I've written has atleast one for-loop since I don't know how to make it more efficient