Why function not push others elements from the sub array

Hello ) Why function do not push other elements which equal elem from sub array ?

  let newArr = [];
  // change code below this line

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

  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ]], "peter"));

Why it is not like this [ [“amy”, “beth”, “sam”], [“dave”, “sean”] ] in case above?

Would you clearly mention what do you want to achieve in this challenge.
Firstly, the code you copied here is missing

funtion filteredArray(arr, elem) {

Secondly, filtered tray has an extra pair of brackets

/// incorrect
console.log(filteredArray([[ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ]], "peter"));
/// correct
console.log(filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter"));

Here is a link to working example of the challenge.
pen
Feel free to play with it.

Hello ) I want to know why function above do not push all sub array which have the element ? Whyconsole.log is not like this [ [“amy”, “beth”, “sam”], [“dave”, “sean”] ] in case above?

The straightforward answer is, it is because of the logic put in there.

if (arr[i].indexOf(elem) === -1){
newArr.push(arr[i]);
  }}

You are pushing array items which don’t have elem in them, if you want to have array of those item which does have elem in the you have to switch the condition like this.

if (arr[i].indexOf(elem) !== -1){
newArr.push(arr[i]);
  }}

That’s it

You can read more about indexOf method here

Remember, you are not pushing the elements from the sub arrays into the newArr, you are pushing the actual sub arrays. Which means you are excluding any sub array (not sub array elements) that contains the string passed to the elem parameter.

It is indexOf that is looping the sub arrays for you (like if you were using a nested loop). If it finds the element it will return the element index, if it does not find the element it will return -1.

Here is the challenge in question, just to be clear for anyone reading this.

1 Like