Swolschblauw Swolschblauw - 1 month ago 4
Javascript Question

Javascript: Grab value before and after specific value in array

I'm trying to grab the value before and after a specific array value.

Like this

var arr = ["model", "color", "handle", "front", "extras"];
var category = "color";

for(i in array) {
if(array[i] == category {
//grab in this case model and handle
}
}


I have tried a number of things such as: adding keys to the array, forcing the array to an object, but nothing helps..

Thanks in advance

Answer

You can use indexOf to get the index of the category. Then knowing the index you can do -1 or +1 to get the values before and after.

If there is no value after or before, say in this example the category was "extras", then it will return undefined. You'll probably need to check if the value is undefined before you use it.

var arr = ["model", "color", "handle", "front", "extras"];
var category = "color";

var i = arr.indexOf(category);

var val1 = arr[i-1];
var val2 = arr[i+1];
Comments