0

I return some of the tests correct but I am not sure why some of my answers come up undefined. I feel like my solution should work with both arrays and strings. Any advice would be appreciated!

Here is the problem: Given a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type.

When the item isn't present or nothing follows it, the function should return nil in Clojure and Elixir, Nothing in Haskell, undefined in JavaScript, None in Python.

Examples provided:

nextItem([1, 2, 3, 4, 5, 6, 7], 3) // 4
nextItem("testing", "t") // "e"

My code:

function nextItem(xs, item) {
for(let i = 0; i < xs.length; i++){
    if(xs[i] === item){
      return xs[i + 1]
    }
  }
}

console.log(nextItem([1, 2, 3, 4, 5, 6, 7], 3)) // 4
console.log(nextItem("testing", "t")) //e
Alex L
  • 4,168
  • 1
  • 9
  • 24
Andrew Lovato
  • 103
  • 2
  • 10
  • 1
    Your code returns the expected results for me. It appears to be working as expected. – Taplar Jun 08 '20 at 14:50
  • You mention that if the same item occurs more then once, that you want to return the next item after the first match. Does that mean if you have 3 matches, you only want to return the second match? – Einar Ólafsson Jun 08 '20 at 15:15
  • Also, if you use a string, do you want to be able to match only one letter or a section of the string? – Einar Ólafsson Jun 08 '20 at 15:34

0 Answers0