0

I have been doing some sorting and still dont get it why the result is []. could you guys help me out what im missing?

I have my raw array object:

var data = [
 {message:'hello', username:'user1'},
 {message:'data', username:'user1'},
 {message:'sample', username:'user2'},
 {message:'here', username:'user2'},
];

my function is:

var chat = [];
function reorder(obj) {
    obj.forEach( function(val, i) {
        if(typeof chat[val.username] === 'undefined') {
            chat[val.username] = [];
            chat[val.username].push(val);   
        }
        else 
            chat[val.username].push(val);
    });
    return chat;
}

and on my console:

reorder(data);

I am expecting to have:

var data2 = [
  'user1': [{message:'hello', username:'user1'}, {message:'data', username:'user1'} ],
  'user2': [{message:'sample', username:'user2'}, {message:'here', username:'user2'} ],
];
4
  • 2
    chat.[val.username] is not valid syntax, aren't you getting a syntax error for that? Is it actually chat[val.username]? Commented Sep 11, 2014 at 6:14
  • Where do you assign the result to data2? Commented Sep 11, 2014 at 6:16
  • Why don't you put the init of 'chat' as first thing into the reorder function? Commented Sep 11, 2014 at 6:17
  • @Barmar yes sorry, I edited my post. assuming you have declared var data2 outside the function Commented Sep 11, 2014 at 6:17

3 Answers 3

1

You can do this easily with reduce:

var data2 = data.reduce(function(acc, x) {
  acc[x.username] = (acc[x.username] || []).concat(x)
  return acc
},{})
/*^
{ user1: 
   [ { message: 'hello', username: 'user1' },
     { message: 'data', username: 'user1' } ],
  user2: 
   [ { message: 'sample', username: 'user2' },
     { message: 'here', username: 'user2' } ] }
*/
Sign up to request clarification or add additional context in comments.

1 Comment

COOL! I didn't know there's a function for this!! thanks! man. how did it do that?!
0

The problem is that you made chat an array. When you look at an array in the console, it only displays the numeric indexes, not the named properties; you have to use console.log(chat) to see the named properties.

Since you want this to be an object with named properties, you should declare it as an object, not an array:

var chat = {};

Comments

0

Use Underscore's _.groupBy:

_.groupBy(data, 'username')

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.