Check For The Presence of an Element With indexOf() -- help

Check For The Presence of an Element With indexOf() -- help
0

#1

Tell us what’s happening:

I understand there are various ways to do something in JS but I feel that I may have complicated things, is there a more straightforward way I should have approached this problem? Or is my way the way you would have approached the problem?

Your code so far


function quickCheck(arr, elem) {
  // change code below this line
if(arr.indexOf(elem) === -1){
  return false;
} else {
  return true;
}
  // change code above this line
}

// change code here to test different cases:
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof


#2

It’s correct. If you really want to shorten it even further:

function quickCheck(arr, elem) {

  return arr.indexOf(elem) > -1;

}

#3

Shorter to use includes method. :grinning:


#4

Although, the purpose of the exercise was to use indexof so that may not pass the test, but is certainly easier.


#5

That is true. I got carried away.


#6

Perhaps, but it’s still good to remind newer coders (like me) of the better functions’ existences.


#7

“Newer” coder. Don’t make me feel so bad.


#8

Just means we still have a lot to learn.