Check if a value exists in an array and get the next value JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 the array for the 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

And the output in the console will be −

myval
false
raja
Published on 21-Nov-2020 06:33:32
Advertisements