B.D.Structures: Iterate Through All an Array's Items Using For Loops [SOLVED]

B.D.Structures: Iterate Through All an Array's Items Using For Loops [SOLVED]
0

#1

I know there are already many solutions for this problem but I wanted to know what’s wrong with my code.

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

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

#2

it solves only two requirements while not for the rest


#3

In the future, use the help button in the challenge. It’ll give a link to the challenge as well.

As for what is wrong with the code, I’d need the link to see what you exactly need.


#4

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.183 Safari/537.36 Vivaldi/1.96.1147.55.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops


#5

I did use the help button but I didn’t create an account yet so after creating the account, I instantly post for help instead using the button help


#6

Ok. Fair enough.

The main problem I see is the usage of slice. When you use slice in a for loop, you have to be careful. Let me try to illustrate the point with pseudocode

forLoopIndex = 0;
arr = [0, 1, 2, 3, 4, 5]
splice(forLoopIndex,1)
//arr is now [1, 2, 3, 4, 5]
forLoopIndex = 1;
splice(forLoopIndex, 1)
//arr is now [1,3,4,5]


#7

I see…thank you for the quick response.
I’ve seen similar answers on another post but thought that my code had nothing to do with it…

Anyway, TYVM.


#8

Good luck on the challenge!