Tell us what’s happening:
What is the shortest solution for this challenge? I completed it using an if else statement but I feel like there is a much better solution for this.
Your code so far
js
function quickCheck(arr, elem) {
// change code below this line
let check = arr.indexOf(elem);
if (check == 1 || check == 2 || check == 3){
return true;
}
else {
return false
}
// change code above this line
}
// change code here to test different cases:
console.log(quickCheck(["squash", "onions", "shallots"], "onions"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.
That is what i did
function quickCheck(arr, elem) {
// change code below this line
if ( arr.indexOf(elem) === -1 ){
return false;
} else {
return true;
}
First, you don’t have to check for the presence of the actual index to see if it’s present.
A simple check > -1 is enough. This is because -1 is the value returned if the item is not present. So
let check = arr.indexOf(elem);
if (check == 1 || check == 2 || check == 3){
return true;
}
else {
return false
}
// can be written like this
// notice I don't need the else statement.
// this is because if the value is present
// the function will exit on return anyways
if (check > -1) return true
return false
Now, the simplest method, and what I would use to check if a value is present would not be the .indexOf method. This won’t pass the final test for obvious reasons.
Instead use .some(). This method will return true if at least one item in the array matches. That means it will only check until it finds the first match. From mdn:
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
" If greater than 0, would that not cause an issue if the indexed element held the first position in the array returning an index of 0? "
For clarity in reference to:
Thank you, yes I meant all the answers checking “greater than 0”. You could do something like
return ((arr.indexOf(elem) + 1) > 0; Though I think checking against -1 is still probably easier for reading.
Checking against 0 satisfies the requirements of the exercise, though I think in application it could cause issues.
If the method returns a negative index, it means that the element in question is out of bounds of the array. Thus a simple conditional statement would suffice to satisfy the primary objective of returning true or false.
if (arr.indexOf(elem) < 0) {
return false;
}
return true;