So this is from the pre-project section in the JavaScript certification. I feel really proud of this code and feel like I’ve come such a long way in the week or two since I started on FCC. I feel like I managed to write this function in a very clean way, but I know there’s always more to learn. What do you guys think of my code in this mini project? What can I improve on? Also, I hope this is alright to post here considering it’s not a full-length project.
var first = [...arr1];
var second = [...arr2];
var result = first.filter(x => second.indexOf(x) === -1);
result = result.concat(second.filter(x => first.indexOf(x) === -1));
return result;
The most important thing is that it works, congrats!
Some suggestions:
Never use var again to declare variables. Get used to using const and let.
The first two lines are creating copies of the arrays passed into the function. You aren’t modifying the arrays though, you are just creating a new array that is a result of filtering the two arrays passed in. So you don’t need the first two lines at all, they are basically using up extra unneeded memory. Just refer to the original arrays passed into the function when filtering to create the new array.
You can combine the last two lines into one line that returns the result of the concat.
Doing all of the above You can reduce your function body down to two nice concise lines.