Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if a value exists in an array and get the next value JavaScript
We are required to write a JavaScript function that takes in an array of literals as the first argument and a search string as the second argument.
The function should search the array for that search string. If that string exists in the array, we should return its next element from the array, otherwise we should return false.
Example
const arr = ["", "comp", "myval", "view", "1"];
const getNext = (value, arr) => {
const a = [undefined].concat(arr);
const p = a.indexOf(value) + 1;
return a[p] || false;
};
console.log(getNext('comp', arr));
console.log(getNext('foo', arr));
Output
The output in the console will be:
myval false
How It Works
The function works by creating a new array with undefined at the beginning, then concatenating the original array. This handles the edge case where we search for the first element - its "previous" element becomes undefined, so the next element calculation works correctly.
Alternative Approach
Here's a more straightforward implementation without array concatenation:
const getNextSimple = (value, arr) => {
const index = arr.indexOf(value);
if (index !== -1 && index
Output
myval
false
false
Comparison
| Method | Handles Edge Cases | Readability |
|---|---|---|
| Array concatenation | Yes | Complex |
| Index checking | Yes | Clear and explicit |
Conclusion
Both approaches effectively find the next value in an array. The index-checking method is more readable and explicit about edge cases, while the concatenation method is more concise but requires understanding the clever array manipulation.
