@maxinimize/

firstRecurringCharacter-exercise

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Google Question
//Given an array = [2,5,1,2,3,5,1,2,4]:
//It should return 2

//Given an array = [2,1,1,2,3,5,1,2,4]:
//It should return 1

//Given an array = [2,3,4,5]:
//It should return undefined


function firstRecurringCharacter(input) {
 if (Array.isArray(input)) {
   let obj = {}
   for (let i = 0; i < input.length; i++) {
     if (obj[input[i]]) {
      return input[i]
     } else {
      obj[input[i]] = true
     }
   }
   return undefined
 }
}

//Bonus... What if we had this:
// [2,5,5,2,3,5,1,2,4]
// return 5 because the pairs are before 2,2

console.log(firstRecurringCharacter([2,5,1,2,3,5,1,2,4]),
firstRecurringCharacter([2,1,1,2,3,5,1,2,4]),
firstRecurringCharacter([2]),
firstRecurringCharacter([2,5,5,2,3,5,1,2,4]))
Native Browser JavaScript