Home > front end >  How to display previous value of a given value from an array in javascript
How to display previous value of a given value from an array in javascript

Time:09-04

How we can display the previous value of given value while value is given from an array and we should display the previous value of it

var theArray = [1,2,3,4,5,6,7,8,9,14,15];
const findValue = (arr, input) => {
  // to do 
}
findValue(theArray , 15)

When we give 15 in input then output would be 14

CodePudding user response:

Try to get the index of the input, then get the previous index :

var theArray = [1,2,3,4,5,6,7,8,9,14,15];
const findValue = (arr, input) => arr[arr.indexOf(input) - 1]
console.log(findValue(theArray , 15))

you should consider the case where input is at the index 0 ...

CodePudding user response:

Is it assumed that the given value is unique? If so, you can just search the array for the value you are looking for (probably using a known search algorithm e.g., binary search) and then return the previous index (if it is not the first item ofc).

CodePudding user response:

const findValue = (arr, input) => {
  let previousItemIndex = arr.findIndex(e => e === input) - 1;
  return previousItemIndex < 0 ? null : arr[previousItemIndex];
}

This will return null if there is no previous item and will find from left to right

  • Related