DEV Community 👩‍💻👨‍💻

Naveen Dinushka
Naveen Dinushka

Posted on

Iterate Through All an Array's Items Using For Loops (freecodecamp notes)

Original Question -> https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops

Question

We have defined a function, filteredArray, which takes arr, a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr. 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.

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line

  // Only change code above this line
  return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Things to know before attempting this question

1.How indexOf works ? The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
2.How to iterate with a for loop
3.How to use .push()

Answer

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;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post