1

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.

3 Answers 3

2
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/

Sign up to request clarification or add additional context in comments.

8 Comments

is it better to use .substr(0,1) or .charAt(0) ? is there one way better than the other ? Thanks !
This is fine. I need to push 'Abcd', 'Anej', 'Aali' into separate array.
I actually have no idea - I've never used charAt.. Dunno why, actually.. I'd like to know if there's a difference, too :D
Why use substr instead of substring, when the first one isn't supported by version 3 browsers yet the exact same results can be obtained with both?
@Niklas version 3 browsers?? hahaha, sorry, I can't avoid to laugh. So we shouldn't use javascript because 8086 machines don't support it :S.
|
1

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

2 Comments

Why use substr instead of substring, when the first one isn't supported by version 3 browsers yet the exact same results can be obtained with both?
version 3 browsers? hahaha. No comments :D
1

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.