I don't understand the solution posted by the user

I don’t understand this line of code. Can someone help explain what is going on? Check the comment after the for loops.

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

  for (let i = 0; i < arr.length; i++) {
//This is the part I don't understand. Why are we asigning -1 to elem? That's not removing the elem from the array, but adding it to the array as -1, right? I don't get it.
    if (arr[i].indexOf(elem) == -1) {
  return newArr;
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Challenge: Iterate Through All an Array’s Items Using For Loops

Link to the challenge:

That’s not an assignment, it’s a comparison.
= is the assignment operator
== is the comparison operator for loose equality
=== is the comparison operator for strict equality

So now this code:

(arr[i].indexOf(elem) == -1)

checks if arr[i].indexOf(elem) is equal to -1

Here’s a link that explains what the .indexOf method returns:

1 Like

This is the assignment " Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed."

If arr contains elem(which is 3)…if this array [1,2,3] contains elem, we want to replace it with -1?

I thought the instructions say “if the number 3 is in the array (elem), remove it from arr.” In other words, we wouldn’t be removing the elem (3), it would be replaced with -1. Why does that work? Is there not a way to remove the 3 from the array?

I guess you could remove it by saying .pop(elem) if it exists in arr. But I haven’t tried that yet.

The logic doesn’t rely on removing anything from the original array that’s passed to the function. Instead, the function builds and returns a new array with all the valid subarrays. Nothing is replaced with -1 anywhere. I’ll add comments to the solution to make it clearer:

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

  for (let i = 0; i < arr.length; i++) { // each step of the loop looks at one of the subarrays
    if (arr[i].indexOf(elem) == -1) { // if elem is not included in the current subarray, ...
      newArr.push(arr[i]); // ...push this subarray to our array of valid items
  return newArr; // return the array with valid items

That’s why the example you’ve posted returns an empty array. The loop goes through all subarrays and checks if 3 is included in them. As 3 can be found in all of them, the if-statement is never true, and nothing gets pushed to the array of valid subarrays (newArr).