Iteration confusion

Hint #1 informs you to use a nested loop to search through all the elements of the nested arrays while this completely contradicts the solution. I’ve tried solving this using one but to no avail. Is Hint #1 invalid or is there a possible way to do this with a nested loop?

3 Likes

yes, it’s weird. I’m removing the word “nested” from there, and it will make sense

1 Like

It’s definitely much easier to do it without nested loops but still it’s possible.

Here’s an example solution using two nested loops. There is probably a better way but that’s what I come up with :slight_smile:

function filteredArray(arr, elem) {
  let newArr = [];
  
  for (let i = 0; i < arr.length; i++) {
    let nestedArr = arr[i];
    let hasElem = false;
    
    for (let j = 0; j < nestedArr.length; j++) {
      if (nestedArr[j] === elem) {
        hasElem = true;
        break;
      } 
    }

    if (!hasElem) {
      newArr.push(nestedArr);
    }
  }
  
 return newArr; 
}
4 Likes

Here’s my solution that worked without realizing I should try to apply indexOf(). I sat down with my developer of a husband and he made me push through this for 30 minutes using only what I can rack up from my noggin.

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

Of course my initial gut was “why can’t I google how to check if an array includes an item?” which was met with a blunt reminder that I’m currently coding for the sake of learning coding.

6 Likes

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

5 Likes