Search code examples
javascriptarrayspushsplice

JavaScript function is not working. indexOf is undefined


function filteredArray(arr, elem) {   let newArr = []; 

Loops through every element of the nested array.

for (let i=0;i<arr.length;i++){     
    for (let j=0;j<arr[i].length;j++){

If the value on the iteration is equal to the argument passed, it is supposed to set a variable x to be equal to the value of the nested array during the ongoing iteration

  if (arr[i][j]==elem){ 
    let x = indexOf(arr[i][j]);

It is supposed to remove the element with index equal to the variable x.

    arr[i][j].splice(x,1);

Then it is supposed to push the remained of the nested array to the new array and then subsequently return the new array.

      newArr[i].push(...arr[i][j]);
      }
    }
  }
  console.log(newArr);
  return newArr;
}

HOWEVER THERE IS AN ERROR THAT SAYS 'indexOf is not defined'

I don't understand why it doesn't work. It return indexOf as undefined for every iteration. Please take a look at comments. Please share your opinion on my code if you don't mind.


Solution

  • indexOf is an array/string method and can be called on an array like array.indexOf(element). In your case your you need to pass the array.

    Also you may skip the indexOf because here variable i and j will give the relevant index of the parent and nested array