I need to create an array of searchable items but I'm not sure whether I should create an array of custom objects or just an array of delimited strings. Can someone give me some advice on which is the better way. Below is an example:
var Arr = [ "Arts Tower|ArtsTower.htm|104",
"Arts Tower|ArtsTower.htm|1203",
"Arts Tower|ArtsTower.htm|Arts Tower"
];
var searchTerm = "tow"
var ArrResults = jQuery.grep(Arr, function(value, index){
return (value.split("|")[2].toLowerCase().indexOf(searchTerm) != -1);
});
or
function Item(name, url, str){
this.name = name;
this.url = url;
this.str= str;
}
var Arr = new Array();
Arr.push(new Item("Arts Tower", "ArtsTower.htm", "104"));
Arr.push(new Item("Arts Tower", "ArtsTower.htm", "1203"));
Arr.push(new Item("Arts Tower", "ArtsTower.htm", "Arts Tower"));
var searchTerm = "tow"
var ArrResults = jQuery.grep(Arr, function(value, index){
return (value.str.toLowerCase().indexOf(searchTerm) != -1);
});
I need to search the array and return back any matches. Which would perform better?
Using Array and Object constructors and pushing items to an array is an overkill (and unnecessary for static data like yours).
Using proprietary encoding (using pipe delimiters) that needs additional processing to parse is also not favorable.
I would go with an array of objects in literal form:
var Arr = [
{ name: "Arts Tower", url: "ArtsTower.htm", str: "104" },
{ name: "Arts Tower", url: "ArtsTower.htm", str: "1203" },
{ name: "Arts Tower", url: "ArtsTower.htm", str: "Arts Tower" }
];
This also brings you closer to a point where you would want to load the data via XHR ($.ajax).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With