Question about how I am getting back non-duplicate numbers

I want to know how the process of .filter(function(element, index, arr) {
return arr.indexOf(element) == index; is working and why it’s only giving me back non-duplicate numbers. Thank you

  **Your code so far**
function uniteUnique(arr ,arr1, arr2) {
return arr
.concat(arr1,arr2)
.filter(function(element, index, arr) {
    return arr.indexOf(element) == index;
  })
}

console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Sorted Union

Link to the challenge:

Before discussing filter I just wanted to point out that you changed the function definition by adding extra parameters and now your function will only work if exactly three arrays are passed into it. The instructions say that the function should be able to accept two or more arrays, so you’ll need to fix this so that it will work with two arrays only or more than three arrays passed in, and you’ll need to change the function definition back to what it originally was:

function uniteUnique(arr) { 

Regarding filter, it goes through each element of the array and returns a new array composed only of those elements that pass the test inside of the filter. Your test is:

arr.indexOf(element) == index

If that test is true then the element will be added to the new array that is returned, otherwise it won’t. You’ve got three variables in this test: arr, element, and index. Do you understand what each of those variables is and where they get their values from? And then you’ll need to know what value the indexOf method returns and what it means. Once you understand all of these then you might see the “trick” being used to determine if an element is a duplicate.

Let us know what you do and don’t understand and then we can go from there.

Hi bbsmooth, yeah you were right it does not work with(arr,arr1,arr2). I got how filter works and thanks for the explanation. I ended up using the spread operator. Here is my code. Let me know what you think of it.

function uniteUnique(…arr) {
return arr
.flat()
.filter(function(element, index, arr) {
return arr.indexOf(element) == index;
})
}

console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));

console.log(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]));

Hey @crisvoss77, that solution looks real good. Now if you want a challenge, you can actually solve this using only flat, no filter, in one really short line of code. I’ll give you a hint. Each of the arrays being passed in can be thought of as a Set of numbers.