0

i been reading for hours trying to make this work but i dont have much knowledge to do it.

I have this js code:

var username=$(this).attr("username");

It pull a list of users f.e (admin, test1, test2, test3)

and i needs to split it into another var like this:

var members = [
    ['admin'],
    ['test1'],
    ['test2'],
    ['test3'],
];

I tried a lot of codes but i cant make it work, thanks in advance!

2
  • Are the usernames seperated by commas? Commented Jul 29, 2012 at 8:07
  • no, they dont ...will include space only Commented Jul 29, 2012 at 8:13

2 Answers 2

4

To get an array of usernames:

var username = $(this).attr("username");
var members = username.split(',');

To get exactly what you've suggested you want (an array of arrays? - I don't think this is actually what you want):

var username = $(this).attr("username");
var membersArr = username.split(',');
var members = new Array();

for (var i = 0; i < membersArr.length; i++)
{
    members[i] = [ membersArr[i] ];
}

To get "[test1]", "[test2]" etc:

var username = $(this).attr("username");
var members = username.split(',');

for (var i = 0; i < members.length; i++)
{
    members[i] = '[' + members[i] + ']';
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. looks ok however i want to to get at the end the user list looks like this: ['admin'],['test1'], ['test2'], ['test3'], - not just commas or spaces .. thanks!
@DJ-237. That doesn't really make sense. What you are describing there is a "list of lists". My second example provides that. Is that what you are really after? My first example gives you a "list of strings".
i'm sorry but im not a pro on this. I got an script that needs at the end a code like this var members = [ ['admin'], ['test1'], ['test2'], ['test3'], ]; The way you did it on second example works but it doesnt includes the username like this ['username'],
@DJ-237 DO you mean like this: "[username]" ?
I works now i just added like this : members[i] = ["['" + membersArr[i] + "'],</br>" ]; thanks a lot for your help!
2

Update
To get the array of arrays,

var username=$(this).attr("username");
var membersArray= username.split(' ').map(function(username){
    return [username];
})
//[["admin"],["test"],["test1"],["test2"]] 

I've added a fiddle here

1 Comment

Thanks, how can i get it into the members var like this? var members = [ ['admin'], ['test1'], ['test2'], ['test3'], ];

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.