Tammy
Tammy

Reputation: 1132

How to return index - 1 from set of an array

How to return index - 1 from set of an array.

Ex:

Function demo(Id) {

Const ids= [1, 2, 3,4,5] ;
// how can I read current index and return index - 1.
return id;
}

Function demo1 (id) ;

Upvotes: 0

Views: 2527

Answers (3)

enkaypeter
enkaypeter

Reputation: 1

If you want to get the current index -1 of each array element, this method does that.

function checkId(id){
    const ids= [1, 2, 3,4,5] ;

    // return -1 if element doesn't exist 
    let Indx = ids.indexOf(id) == -1 ? -1 : ids.indexOf(id) -1; 

    //do this if you want the array element
    //let arrEl = ids.indexOf(id) == -1 ? -1 : ids[ids.indexOf(id) -1];

    return Indx;
}

console.log(checkId(3)) // returns 1
console.log(checkId(6)) // returns -1

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65845

To get the current index of an element in an array, use the indexOf() array method. This method returns -1 when the element you are trying to find does not exist in the array.

let index = null;

function demo(id) {
  const ids= [1, 2, 3,4,5];
  // how can I read current index and return index - 1.
  index = ids.indexOf(id);
  return -1;
}

console.log(demo(1), index);
console.log(demo(2), index);
console.log(demo(3), index);
console.log(demo(4), index);
console.log(demo(5), index);
console.log(demo(6), index);  // -1 because 6 isn't in the array
console.log(demo(0), index);  // -1 because 0 isn't in the array

Upvotes: 0

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You can do this by indexOf function see below...

function demo(id) {    
 const ids= [1, 2, 3,4,5] ;
 var index = ids.indexOf(id);
 var res = i - 1;
 return res;
}

Upvotes: 1

Related Questions