1

How can we display the previous value of given value while the 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 the output would be 14.

3
  • 1
    what if you look for the previous from 1? please add your code, you tried. Commented Sep 3, 2022 at 8:50
  • @NinaScholz i'm stuck to create logic for this problem Commented Sep 3, 2022 at 8:52
  • find index of wanted value, decrement index, check it and get value from it. Commented Sep 3, 2022 at 8:54

3 Answers 3

1

Try to get the index of the input, and 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...

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

Comments

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

This will return null if there isn't any previous item and will find from left to right.

Comments

0

If it is assumed that the given value is unique, 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 of course).

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.