2

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?

Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
blackdaemon
  • 715
  • 4
  • 16
  • 41
  • Possible duplicate of [How do I check if an array includes an object in JavaScript?](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Lieu Zheng Hong Mar 07 '17 at 07:08

5 Answers5

2
  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.

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
1

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);
brk
  • 46,805
  • 5
  • 49
  • 71
0

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));
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0
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

MK4
  • 665
  • 7
  • 21
0

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));
Rajesh
  • 22,581
  • 5
  • 41
  • 70