Diff Two Arrays question about indexOf

how does second.indexOf(first[i]) being ===-1 return the symmetric difference. What does the -1 mean in this situation. I think I remember -1 meaning that that it’s not a position in the array because it’s not there. Please help me understand this a bit better thank you.

  **Your code so far**
function diffArray(arr1, arr2) {
let myArr=[];
function wowArray(first, second){
for(let i = 0; i < first.length; i++){
if (second.indexOf(first[i]) === -1){
myArr.push(first[i]) 
}
}
}
wowArray(arr1,arr2)
wowArray(arr2,arr1)
return myArr
}

console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
  **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: Diff Two Arrays

Link to the challenge:

Is this code just copied from one of the solutions?

You can read about indexOf here: Array.prototype.indexOf() - JavaScript | MDN

A result of -1 means that the item wasn’t found.

1 Like

By the way

list.indexOf(item) === -1

is fuctionally equivalent to

!list.includes(item)

I find includes to be much easier to read if you’re only checking for existence and don’t care about the index. On the other hand, if you plan to actually use the index returned from indexOf, then indexOf is the right choice.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.