Created
April 24, 2015 04:52
-
-
Save keif/bcc3bbc3764d073dbf99 to your computer and use it in GitHub Desktop.
Old School vs. New School: Double for loop vs. a dictionary method for getting the unique values from array.
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
// old school double loop | |
// quadratic O(n^2) inefficiency | |
var unique = function(array) { | |
var arr = [], | |
len = array.length; | |
for (var idx = 0; idx < len; i++) { | |
for(var jdx = i + 1; jdx < len; jdx++) { | |
if (array[idx] === array[jdx]) { | |
j = ++i; | |
} | |
} | |
arr.push(array[i]); | |
} | |
return a; | |
}; | |
// smarter new school | |
// better for larger arrays | |
var unique = function(array) { | |
var obj = {}, | |
idx, | |
len = array.length, | |
res = []; | |
for (idx = 0; idx < len; idx += 1) { | |
obj[array[idx]] = array[idx]; | |
} | |
for (idx in obj) { | |
res.push(obj[idx]); | |
} | |
return res; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment