1

I have an array of items that looks, for instance, like this:

[el, el, *el*, TARGET, TARGET, TARGET, *el*, el, el, el]

I can't find a way to get previous and subsequent elements relative to the TARGET sequence, i.e both *el*. Number of TARGET element in sequence may vary but the sequence is always concrete i.e TARGET, el, TARGET does not happen. I have access to lodash methods, too, but I couldn't find the correct way to achieve this.

3
  • 1
    You can do a better explanation ? Commented Mar 18, 2016 at 17:41
  • A combination of indexOf and lastIndexOf? Commented Mar 18, 2016 at 17:43
  • 1
    show the array with real values Commented Mar 18, 2016 at 17:43

1 Answer 1

2

You can use indexOf and lastIndexOf:

var arr = ['el', 'el', '*el*', 'TARGET', 'TARGET', 'TARGET', '*el*', 'el', 'el'];

var first = arr[arr.indexOf('TARGET') - 1];
var second = arr[arr.lastIndexOf('TARGET') + 1];

document.write(first + '<br/>');
document.write(second);

Sign up to request clarification or add additional context in comments.

1 Comment

@dandavis the question specifically says that does not happen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.