2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Check For The Presence of an Element With indexOf()
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Check For The Presence of an Element With indexOf()
|
2018-10-12 15:37:13 -04:00
|
|
|
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
function quickCheck(arr, elem) {
|
2019-07-24 00:59:27 -07:00
|
|
|
if (arr.indexOf(elem) >= 0) {
|
2018-10-12 15:37:13 -04:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
console.log(quickCheck(["squash", "onions", "shallots"], "mushrooms"));
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Code Explanation
|
|
|
|
- A simple `if-statement` can be used to check whether or not the value returned by the `indexOf()` function is less than 0.
|
|
|
|
- Once the value is discovered then you can return either `true` or `false`.
|
|
|
|
- demonstrates how a simple `if-statement` can return the correct result.
|
|
|
|
</details>
|
|
|
|
|
|
|
|
<details><summary>Solution 2 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
function quickCheck(arr, elem) {
|
2019-07-24 00:59:27 -07:00
|
|
|
return arr.indexOf(elem) >= 0 ? true : false;
|
2018-10-12 15:37:13 -04:00
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
console.log(quickCheck(["squash", "onions", "shallots"], "mushrooms"));
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
2018-11-22 22:14:40 +01:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Code Explanation
|
|
|
|
- demonstrates how the problem can be solved using the `? : (conditional)` operator.
|
|
|
|
</details>
|
|
|
|
|
|
|
|
|
|
|
|
<details><summary>Solution 3 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-11-22 22:14:40 +01:00
|
|
|
```javascript
|
|
|
|
function quickCheck(arr, elem) {
|
|
|
|
return arr.indexOf(elem) != -1;
|
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
console.log(quickCheck(["squash", "onions", "shallots"], "mushrooms"));
|
2018-11-22 22:14:40 +01:00
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
#### Code Explanation
|
|
|
|
- demonstrates how the problem can be solved by directly returning result of the comparison.
|
|
|
|
</details>
|