Skip to content
Advertisement

Finding all the elements in a list between two elements (not using index, and with wrap around)

I’m trying to figure out a way to find all the elements that appear between two list elements (inclusive) – but to do it without reference to position, and instead with reference to the elements themselves. It’s easier to explain with code:

I have a list like this:

JavaScript

And I want a function that would take, two arguments corresponding to elements eg. f('a','d'), and return the following:

JavaScript

I’d also like it to wrap around, eg. f('d','b'):

JavaScript

I’m not sure how to go about coding this. One hacky way I’ve thought of is duplicating the list in question (['a','b','c','d','e','a','b','c','d','e']) and then looping through it and flagging when the first element appears and when the last element does and then discarding the rest – but it seems like there would be a better way. Any suggestions?

Advertisement

Answer

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement