1

I am looking for some general advice about how I should be thinking to go about doing this.

What I need to do is take an object that has "usernames" : userId, etc.. and split them into separate objects or arrays with each object only containing usernames that start from a certain letter.

So right now I have:

allusers = {"adam292":10302, "alex92":12902, "briannv999":10302,  "sandra127":11102, "sam11":100 }

but I need to split them into their own objects or arrays like the following:

ausers = { "adam292":10302, "alex92":12902 }

busers = { "briannv999":10302 }

susers = {"sandra127":11102, "sam11":1002 }

I am doing this because I need to display a dialog box that also shows the letters a - z which would be links that you can click to display users that start with that letter.

Any advice is very much appreciated!

1
  • This is the classic "groupBy" problem, where the dimension you want to group along is defined by the first character of the name. Search SO or elsewhere for "JavaScript group by" or similar. Commented Apr 7, 2016 at 7:29

2 Answers 2

4

Here is one way to do it:

Working Fiddle

looping through the object we grab the first letter and check to see if we have a key for it in our users object, if not we make one and assign an array (containing the user data) to it, if yes we push to that array:

var users = {};

for (var user in allusers) {
  var firstLetter = user.slice(0,1);
  if (users[firstLetter]) {
    users[firstLetter].push([user, allusers[user]]);
  }
  else {
    users[firstLetter] = [[user, allusers[user]]];
  }
}

The output of the code above using your example object is the following:

{
  a: [["adam292", 10302], ["alex92", 12902]],
  b: [["briannv999", 10302]],
  s: [["sandra127", 11102], ["sam11", 100]]
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can do this in a loop:

letter2users = {}
for (var uname in allusers) {
    if (!letter2users[uname[0]]) {
        letter2users[uname[0]] = [];
    }

    letter2users[uname[0]].push(allusers[uname]);
}

# access this by using letter2users.a lettersusers.b

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.