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?

1

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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);

2 Comments

You are looping over array twice. Its better to save index value in one variable
I aagree with you
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));

Comments

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));

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.