Last active
May 25, 2016 20:59
-
-
Save jmsevold/3de4fba59ad6cce98aa2ca11d141888c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Find the only element in an array that only occurs once. | |
// create an object storing the keys as the numbers, and the values as the occurrence | |
// find the key that has a value of 1, and return that key | |
let list = [1,1,2,2,3,3,4,5,5,6,6]; | |
let uniqueNum = (nums) =>{ | |
let numObj = numCount(nums); | |
for (var prop in numObj) { | |
if (numObj[prop] === 1) { | |
console.log(prop); | |
} | |
} | |
}; | |
var numCount = (list) => { | |
return list.reduce((acc,current) =>{ | |
var numKey = current.toString(); | |
acc[numKey] === undefined ? acc[numKey] = 1 : acc[numKey] += 1; | |
return acc; | |
},{}); | |
}; | |
uniqueNum(list); | |
// with a double for loop, the number will be the one with a count of 1, indicating it was only compared against itself in the | |
// double for loop | |
let doubleForUniq = (list) => { | |
let target; | |
let count = 0; | |
list.forEach((num) => { | |
target = num; | |
count = 0; | |
list.forEach((num2) => { | |
if (num === num2) { count += 1 } | |
}); | |
//console.log('-----------------------------'); | |
if (count === 1) { console.log("found it!!!!",target) } | |
}); | |
} | |
console.log(doubleForUniq(list)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment