In order to build the array of strings necessary for JQuery autocomplete, I’m traversing an array of objects and flattening it into an array of unique strings. I’m doing this about how you might expect:
var input = [{prop1:'value1', prop2: 'value2'}];
$.each(input, function (index, value) {
$.each(value, function (i, v) {
if (v != undefined && v != null && v != '' && ($.inArray(v, keywords) < 0)) {
keywords.push(v);
}
});
});
The problem is that it performs poorly for large input sets, and blocks the UI while it’s running. How can I make this better?
You’ve got an O(n^2) algorithm there. Looking through that keywords array over and over again is going to get really slow (as you’ve noticed).
Instead, keep the keywords as an object:
Note that your tests of “v” against undefined, null, and the empty string can be replaced by letting JavaScript check it’s truthiness. That’s not always the right thing, but it’s fine here.
You can also keep the keywords in an array, if you like. Just don’t search the array to determine whether a keyword has been seen yet.