Is there a way to select an array object relevant to another?

So let’s say I have an array with a name of test. If I assign it like this: var test = [1, 2, 3, 4]; Is there a way to choose the number 2 by saying which number is below 3?

Sorry if I didn’t explain it good enough, if theres a part you didn’t understand tell me and I’ll try to explain better.

Answer

You can use indexOf to find the index of 3 and then just count one index down from there:

var test = [1, 2, 3, 4];

console.log(
    test[test.indexOf(3) - 1]
);

Leave a Reply

Your email address will not be published. Required fields are marked *