Skip to content

Instantly share code, notes, and snippets.

@keif
Created April 24, 2015 04:52
Show Gist options
  • Save keif/bcc3bbc3764d073dbf99 to your computer and use it in GitHub Desktop.
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.
// 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