How to know which elements are before and after a given element in the array?

-1

I have an array:

Const array = [1,”a”,3];

I want to know how I can check which elements are before and after "a".

    
asked by anonymous 11.06.2018 / 00:47

2 answers

2

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);
    
11.06.2018 / 01:24
1

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.

    
11.06.2018 / 00:53