0

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

  • 2
    Use `indexOf` to find the element. [`for..in` shouldn't be used on arrays](http://stackoverflow.com/q/500504/5743988). – 4castle Oct 20 '16 at 20:58

2 Answers2

2

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];
Kolby
  • 2,775
  • 3
  • 25
  • 44
0

You might do as follows;

var arr = ["model", "color", "handle", "front", "extras"],
   doit = (arr,str) => { fi = arr.indexOf(str);
                         return [arr[fi-1],str,arr[fi+1]];
                       };

console.log(doit(arr,"model"));
Redu
  • 25,060
  • 6
  • 56
  • 76