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

Asked

Viewed 80 times

-1

i have an array:

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

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

2 answers

1

You can use the functions filter and index. It goes 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 possess the value [1] whose position is less than the position of the element 2. You could also utilize the magic of Arrows functions and have:

const array = [1,"a",3]
const teste = array.filter((value, index, array) => index < array.indexOf("a"))

That has the same result.

  • Thank you Joao, you helped me a lot, but I have a question.. if I have the array [1,2,"a",3] and want to return only 2? From what I understand of your code, it returns the correct 1,2?

  • 1

    Do you speak return only 2? The filter function will return you a new array with all the components of the old array that pass a certain test. So, if you have the array [1,2,”a”,3], the code above will return you [1,2]. If you wanted him to just come back [2] you would have to make a modification on parole, which in that case would no longer be index < array.indexOf("a") and would become index < array.indexOf("a") && value == 2. Note that in the parameters, value is the value saved in the array, index the position and array the array being iterated.

1


With a simple .indexOf you take the position of the item, then subtracting by 1 you take the previous item and adding +1 you take the later item:

const array = [1,"a",3];

var pos = array.indexOf("a");
var antes = array[pos-1];
var depois = array[pos+1];

console.log(antes, depois);

  • and to catch the before the after?

  • Huh? I don’t get it

  • right answer: var antesdodepois = array[pos-1+1]; or var antesdodepois = array[pos-0]; hahaha or simply var antesdodepois = array[pos];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.