Reputation: 8726
friends.
I have an array and it contains some string values. ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array". if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
Upvotes: 1
Views: 2219
Reputation: 30002
You could do it using each()
and charAt
:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});
Upvotes: 1
Reputation: 18344
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
Upvotes: 1
Reputation: 8851
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array
and put them into an object containing the arrays indexed by the first letter of the elements in All_array
, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
Upvotes: 2