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
  • 18,263
  • 7
  • 55
  • 75
blackdaemon
  • 755
  • 5
  • 19
  • 44
  • 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
  • 120,458
  • 37
  • 198
  • 307
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
  • 48,835
  • 10
  • 56
  • 78
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
  • 376,160
  • 25
  • 347
  • 392
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
  • 725
  • 8
  • 24
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
  • 24,354
  • 5
  • 48
  • 79