Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of objects vs array of delimited array of strings

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?

like image 726
Richard Banks Avatar asked Mar 15 '11 11:03

Richard Banks


1 Answers

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).

like image 177
Ates Goral Avatar answered Nov 02 '22 11:11

Ates Goral