I have an array:
Const array = [1,”a”,3];
I want to know how I can check which elements are before and after "a".
I have an array:
Const array = [1,”a”,3];
I want to know how I can check which elements are before and after "a".
With a simple .indexOf
you get the position of the item, then subtracting by 1 you take the previous item and adding +1 you get the item later:
const array = [1,"a",3];
var pos = array.indexOf("a");
var antes = array[pos-1];
var depois = array[pos+1];
console.log(antes, depois);
You can use filter and indexOf . It looks something like this:
const array = [1,"a",3]
const arrayReduzida = array.filter(function (value, index, array) {
return index < array.indexOf("a")
})
In the above example, the variable arrayReduzida
will have the value [1]
whose position is less than the position of the 2
element. You could also use the arrows functions magic and have:
const array = [1,"a",3]
const teste = array.filter((value, index, array) => index < array.indexOf("a"))
That has the same result.