DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

1

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️