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?
let x = ["", "comp", "myval", "view", "1"];
if (x.indexOf(yourVal) >= 0) {
let nextValue = x[x.indexOf(yourVal) + 1];
} else {
// doesn't exist.
}
Note : you won't get next values if your values is last value of array.
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);
You could use a function and return undefined if no next value.
function getNext(value, array) {
var p = array.indexOf(value) + 1;
if (p) {
return array[p];
}
}
let x = ["", "comp", "myval", "view", "1"]
console.log(getNext('comp', x));
console.log(getNext('foo', x));
let x = ["", "comp", "myval", "view", "1"]
let nextIndex = x.indexOf('comp') > -1 ? x.indexOf('comp') + 1 : -1;
basically, check if "comp"
exists in x
, if true
i.e > -1
then it returns indexOf("comp") + 1
which is the next item else returns -1
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));