# I solved Diff Two Arrays, but what happened next is crazy!

I solved Diff Two Arrays, but what happened next is crazy!
0

#1

I’ll admit to a click-baity title here, but I would like some help thinking through the solution I came up with for the Diff Two Arrays scripting challenge.

I’ve included my script below. Technically, it passes all of the tests. However, instead of returning just one instance of the symmetric difference of the two arrays, it returns that instance the equivalent number of times as the length of my concat array (newArr). With the diffArray below the solution should be [4, 6]. But my script returns [4,4,4,4,4,4,4,4,4,4,6,6,6,6,6,6,6,6,6,6].

``````function diffArray(arr1, arr2) {
var newArr = [];

var solution = [];

//Merge both subarrays into one unified array
newArr = arr1.concat(arr2);

var sorting = newArr.filter(function (elem) {
for (var i = 0; i < newArr.length; i++) {
if (arr1.indexOf(elem) < 0 || arr2.indexOf(elem) < 0) {
solution.push(elem);
}
}
});

return solution;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5, 6]);
``````

#2

You need to use triple backticks to post code to the forum.
See this post for details.

#3

Thank you, ArielLeslie. This is my first post in the forum. Good to know about back ticks.

#4

filter already sorts by element, so you don’t need the forEach inside of filter.
SPOILER BELOW
.
.
.
.
.
.

``````    function diffArray(arr1, arr2) {
var newArr = [];

var solution = [];

//Merge both subarrays into one unified array
newArr = arr1.concat(arr2);

var sorting = newArr.filter(function (elem) {

if (arr1.indexOf(elem) < 0 || arr2.indexOf(elem) < 0) {
solution.push(elem);
}

});

return solution;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5, 6]);
``````

#5

Mr Array has some duplicate invitations that he wants to remove. So he goes to Mr. Filter for help. Mr. Filter takes each invitation, passes it to Mr. Predicate and asks: should it stay or should it go?
But Mr Predicate says nothing, he just takes the invitation to Mr. Loop and does some sneaky business with him. There’s a lot of pushing there.

#6

So, if I understand this correctly, filter() essentially does the work of a for() loop itself in this situation? Thank you for your help. Removing the for() loop works!

#7

The forum supports `[spoiler]` tags. I have added them to your post.

#8

Thank you, I had seen that but wasn’t sure how it was used, now I know.

#9

Yep, it’s worth spending time looking for places where things like map and filter can be used in place of current forEach loops in your code.