Hello i have this array :
What is the best approach to extract region[],city[] and area[] considering that this array could grow like:region5, city5,area5,region6,city6,area6?
Thank you
I would do something like this :
function getData(array){
var cities = [], regions = [], areas = [],
item, i, j, value,
hash = array.slice(5, array.length); //we don't need the first 6 values.
//assuming the data always comes in this order.
hash.sort();//to get values in the right order
for(i= 0, j = hash.length; i<j; i++){
item = hash[i];
value = item.split("=")[1];
if(item.indexOf("a"=== 0)){
areas.push(value);
}
else if(item.indexOf("c"=== 0)){
cities.push(value);
}else if(item.indexOf("r"=== 0)){
regions.push(value);
}
}
return {
areas : areas,
cities : cities,
regions : regions
};
}
Here's the way I would do it:
var strings = ["city1=Bellevue", "city2=Seattle", "area1=Sound", "area2=Boston"];
var keys = {};
for(var i = 0; i < strings.length; i++)
{
var parse = /^([a-z]+)[0-9]+\=([a-z]+)$/i
var result = parse.exec(strings[i]);
var key = result[1];
var value = result[2];
if(!keys[key]) keys[key] = [];
keys[key].push(value);
}
alert(keys['city']);
alert(keys['area']);
This assumes the order of the keys doesn't matter (I ignore the number at the end of each key). You could, of course, modify the code to parse out that number and use it as an array index as well. I'll leave this up to you, hoping this will at least get you started.
var info = ["cities1=Bellevue", "cities2=Seattle", "areas1=Sound", "areas2=Boston", "regions1=Region1", "regions2=Region2"];
var cities = [];
var areas = [];
var regions = [];
for(var i = 0; i < info.length; i++){
var item = info[i];
if(/cities\d+/.test(item)){
cities.push(item.split("=")[1]);
}
else if(/areas\d+/.test(item)){
areas.push(item.split("=")[1]);
}
else if(/regions\d+/.test(item)){
regions.push(item.split("=")[1]);
}
}
Assuming the array will be always like the example shown. Otherwise please add condition checks where the item is split.
city[]
array, all "areaX" elements toarea[]
area, etc?