Intermediate Algorithm Scripting - Diff Two Arrays

Why does this code not work?

function diffArray(arr1, arr2) {
  const newArr = [];
  for (let i=0;i<=arr1.length;i++)
if (arr2.indexOf (arr1[i]===-1)) {
newArr.push(arr1[i])
};
 return newArr
};

console.log(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]));

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Diff Two Arrays

Link to the challenge:

Here is some formatting so that it’s easier for others to understand your code.

function diffArray(arr1, arr2) {
  const newArr = [];
  for (let i = 0; i <= arr1.length; i++) {
    if (arr2.indexOf(arr1[i] === -1)) {
      newArr.push(arr1[i]);
    }
  }
  return newArr;
}

Why these loop bounds?

You are missing the part where you find the elements of arr2 that aren’t in arr1

I guess I am wrong but I used those loop bounds because I wanted to loop through all elements in the array, I thought they would do that.

But i <= arr.length isn’t what you used for your last loop. You used <

You mean the loop from the last question? In that loop I trying to find the numbers between the two elements so I did not want the= sign in the range because I did not want to loop to the last element. But in this loop I’m trying to reach all the elements so I include the = sign. Am I wrong?

You seem to have a lot of trouble with loops. I would review them

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