Please help me with this javascript code

This code below filters the elements of elem ( the second argument ) from arr ( which is the first argument fo this function.
My question is what happens when “if condition” returns true not -1 (technically false).
does this piece of code still filter the items of elem?

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
 for(let i=0; i<arr.length; i++){
   if (arr[i].indexOf(elem)==-1){
      newArr.push(arr[i]);
   }
  
 }
  // Only change code above this line
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

It looks like your current code only adds the arrays that don’t have the value of elem to the newArr. Is this what you want to happen?

This condition will only be true if the element does not exist in the array. If it does exist, then the if statement will be ignored and the for loop will move on to the next iteration.

1 Like
 for(let i=0; i<arr.length; i++){
   if (arr[i].indexOf(elem)){
      newArr.push(arr[i]);
   }
  
 }

under this condition, the arrays which contain the elem at index 0 will not be added to newArr as 0 is falsy. but otherwise it works fine means other than 0 index(& -1 if not available at all). Neg numbers are not falsy in js by default.

1 Like