1

I have an array of ID's and organizations like so:

var ids = ['1','2', '3'];
var orgs =
    [ 
      { name: "Org 1", id: 1 },
      { name: "Org 2", id: 2 },
      { name: "Org 3", id: 2 }
    ]

I want to loop through these to output something like this:

{
    1: [
        {name: "Org 1", id: 1}
    ],
    2: [
        {name: "Org 2", id: 2},
        {name: "Org 3", id: 2}
    ]
}

I tried this without success:

var results = orgs.forEach(function (org) {
    if (results[org.id]) {
        results.push(org)
    } else {
        results[org.id] = [org]
    };
});
2
  • Your results is an invalid structure. { [ ] } is invalid, you can't have an object without keys. Commented Dec 3, 2014 at 20:56
  • Thanks @RocketHazmat - I think i've updated accordingly. Commented Dec 3, 2014 at 21:09

2 Answers 2

11

If you don't want to use a library like Underscore, Ramda, or Lo-Dash, then it's simple enough to write this using reduce:

var results = orgs.reduce(function(results, org) {
    (results[org.id] = results[org.id] || []).push(org);
    return results;
}, {})
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Scott - exactly what I'm searching for.
But notice that libraries also make this easy. With Ramda you could just do R.groupBy(R.prop('id'), orgs);. And if you wanted a reusable function, it would just be var groupById = R.groupBy(R.prop('id'));. Lo-Dash and Underscore offer fairly similar functionality.
Slightly newer syntax var results = orgs.reduce((results, org) => ({...results, [org.id]: org}), {})
@Headless: that will only allow one entry per key. The question requests an array of them, and in fact, "2" will have two entries in the sample data.
1

you should use underscore and just return your id

http://underscorejs.org/#groupBy

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
// => {1: [1.3], 2: [2.1, 2.4]}

you might also want to take a look at lo-dash

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.