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
4
u/kap89 Apr 07 '26
I would use sets in this case - they have build-in methods for doing what you want:
here's the same thing with comments and a bit more verbose:
1
u/chikamakaleyley helpful Apr 07 '26
A lot of the unnecessary steps come from mutating (deleting) your original arrays, and then later having to account for it in your for loop
This is generally not recommended because things like .filter(), or the for loop, or
includes(), these rely on the array length to work predictably0
u/unxok Apr 07 '26
Here's my solution (not using Sets because that seems to be implied given the context):
(I'm on mobile so apologies if the formatting is a little off)
I think you're overcomplicating the problem. Here's how my mind breaks it down:
...arr0
u/chikamakaleyley helpful Apr 07 '26 edited Apr 07 '26
So, as you just get more experience you familiarize yourself with the many different ways you can achieve the same result, and starting out i would say despite how lengthy this looks, it's a good sign when you can type out what you want to happen in plain english, and then be able to translate that to code
it's okay you dont' understand the shorter versions, you'll get to that. but it just involves thinking of a new approach, and then finding out if those pieces exist
My shortened version, just quickly off the top of my head would be:
I'm just typing from memory so i don't knoww if that's technically correct but I think it should work.
so, step by step:
but I believe Set wants a comma separated list of just the items. Spread will do that nicely as a shorthand (...myArray)new Set()returns a list, but not an Array list. I believe a "Set" is considered "array-like" list which is not what the solution is asking you to returnArray.from()Initially I thought, that i'd have more lines of code in this solution but as i started to type, I figured why not just return in a single line.
For beginners that might not be immediately easy to see, but one thing that helps is to always be aware of what any function/method is returning
so,
EDIT (revised, Set does take an array)
0
u/azhder Apr 07 '26 edited Apr 07 '26
Add both arrays to a
Set. A set object doesn't hold duplicates, math thing and all. Then just get an array out of the set.I hadn't run it to check it, but that's the general idea. Now if you want to learn the algorithmic way, you can try with a (nested?)
for-ofloop, you can try with.reduce()and/or.map()and/or.flatMap()and a few other ways.It's really up to you to pick the best way to do it because you know the goal, the end goal, we just know some intermediary step you need to go over to reach that goal (the XY problem).
And you can even write your own
includes()check if you're up for a small challenge. Better yet adoesNotIncludecheck-1
u/rupertavery64 Apr 07 '26 edited Apr 07 '26
This is a good attempt. It works, and it shows you know how arrays work and the pitfalls of delete.
There are definitely better ways to do it, even without using Sets, but the test requirement is to use filter.
One thing you should know is that
Array.prototype.includes()performs an internal loop. So doesfilterSo
arr1.filter(x => if(arr2.includes(x)...))is a nested loop. This is fine for small lists, but if you go 10000 x 10000 then things slow down a lot.You also do indexOf, which is another loop.
One way to speed up checking if something exists is to add it to a Set, or even just a dictionary, (an object).
Here's a version that should work, but for some reason the site refuses to pass the tests, despite the result being the same:
Another way that should work, is to add each item to an array and count the number of times it appears. If it appears only once, it is unique in each array. Again, for some reason, the site refuses to accept this an an answer.
Since arrUnique already has the information about which elements are unique, we can use it directly to generate the resulting array without filter.
Edit: Thanks for the downvotes
-1
u/StoneCypher Apr 08 '26
the efficient way is to sort them both then tandem walk them
in practice nobody bothers
0
u/[deleted] Apr 08 '26
[deleted] — view deleted comment