Iterating over an Array and checking if an item exist

Tell us what’s happening:

Well obviously my code works just fine, but I was wondering is there a better way to do this . :blush:


function filteredArray(arr, elem) {
let newArr = [];
for(let i = 0; i < arr.length; i++) {
  const indexOf = arr[i].indexOf(elem)
  console.log(`Iteration ${i}: [${arr[i]}] - found elem at: ${indexOf}`)
  if(indexOf === -1) {
    newArr.push(arr[i])
  }
}
return newArr;
}

filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3);

Challenge: Iterate Through All an Array’s Items Using For Loops

Link to the challenge:

Well, since the instructions say you have to use a for loop then your options for making this “better” are pretty limited :slight_smile: But you do technically have an unnecessary variable in there that you can get rid of. I think maybe you have it in there for the sake of the console.log?

1 Like

Yeah you are right! I used that variable for my console.log() ^^

Thanks for your comment :heart:

You could use a for…of statement since you’re hitting all items in the array.

And then a nitpick, I think includes() is easier to grok than indexOf() when checking for existence since you don’t have to understand what -1 means.

1 Like

Not making it better but using indexOf feels a little bit “cheaty” to me. I’d rather see another for loop myself to show full understanding of the topic. Just my two cents!

1 Like

I’m gonna consider your words and try to figure out another way to get same results with more efficient and cleaner code!

Thank you.

1 Like

On the topic of clean code I can highly recommend the book “Clean Code” by Robert Martin. The examples are all in Java but the principles are sound. I’ve been a professional developer for 27 years, and reading it at the moment is making me change the way I code. We are always learning in this industry.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.