I have an Array let x = ["", "comp", "myval", "view", "1"].
I want to check first whether or not the value "comp" exists in the array, and if it does then get the very next value. Any idea?
I have an Array let x = ["", "comp", "myval", "view", "1"].
I want to check first whether or not the value "comp" exists in the array, and if it does then get the very next value. Any idea?
You can do like this
var x=["","comp","myval","view","1"],
l=-1!==x.indexOf("comp")?x[x.indexOf("comp")+1]:"no value";
console.log(l);
An alternate can be to have first element as undefined and then fetch index of search value and return array[index + 1].
Since first element is undefined, for any non matching case, index would return -1, which will fetch first element in array.
This approach involves creating new array and using if(index) return array[index] would be better, still this is just an alternate approach of how you can achieve this.
function getNext(value, array) {
var a = [undefined].concat(array)
var p = a.indexOf(value) + 1;
return a[p];
}
let x = ["", "comp", "myval", "view", "1"]
console.log(getNext('comp', x));
console.log(getNext('foo', x));