Tell us what’s happening:
Hello I’m currently on the second challenge of the intermediate algorithm scripting section. I have ran into a problem and that is me trying to figure out how to properly filter out the array of number(or items).
I have searched on the web and looked on specific pages about removing duplicates from an array using .filter, however despite me doing the same thing I read from the page or thread it still doesn’t filter out the duplicates in the array. I have tried different methods and ideas but still it comes out with the full array as if nothing happened. My code is down below.
Does anyone know why this filter in my code doesn’t work? The filter works in some test file I made but not here. Not sure if it has anything to do with pushing the concatenated arrays into newArr. If there’s any links to pages I can read on about this then they would be extremely helpful.
Your code so far
function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
// Merge both arrays into one then push it into newArr
newArr.push(arr1.concat(arr2));
// Remove all duplicates leaving only unique items
var filteredDups = newArr.filter((item, index) => newArr.indexOf(item) == index);
// Comes out with [1, 2, 3, 5, 1, 2, 3, 4, 5] when I want it to contain only unique items
console.log(filteredDups);
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
.
Challenge: Diff Two Arrays
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays