1

I have an array in the following format

[
{
    "duedate": "15-feb-2014",
    "alias": "electronus",
    "agent": "anonymous",
    "name": ""
},
{
    "duedate": "15-feb-2014",
    "alias": "luminous",
    "agent": "anonymous",
    "name": ""
},
{
    "duedate": "16-feb-2014",
    "alias": "GSM",
    "agent": "anonymous",
    "name": ""
}
]

Underscore group by method allows me to group the array using the properties and in my case using due date. This will return an array like this

{
"15-Feb-2014": [
    {
        "duedate": "15-feb-2014",
        "alias": "electronus",
        "agent": "anonymous",
        "name": ""
    },
    {
        "duedate": "15-feb-2014",
        "alias": "luminous",
        "agent": "anonymous",
        "name": ""
    }
],
"16-Feb-2014": [
    {
        "duedate": "16-feb-2014",
        "alias": "GSM",
        "agent": "anonymous",
        "name": ""
    }
]
}

Is there a possibility that I could have an array like this:

[
{
    "duedate": "15-feb-2014",
    "myValues": [
        {
            "duedate": "15-feb-2014",
            "alias": "electronus",
            "agent": "anonymous",
            "name": ""
        },
        {
            "duedate": "15-feb-2014",
            "alias": "luminous",
            "agent": "anonymous",
            "name": ""
        }
    ]
},
{
    "duedate": "16-feb-2014",
    "myValues": [
        {
            "duedate": "16-feb-2014",
            "alias": "GSM",
            "agent": "anonymous",
            "name": ""
        }
    ]
}
]

So I could have multiple array values inside each due date so I could parse it to fill a template which I can't change.

I have been struggling with this for quite some time. Any help would be gratefully recieved.

1
  • There must be a way, can yout show us your code so far? Commented Feb 15, 2014 at 4:11

1 Answer 1

4

You just need to call map() after groupBy()...

var groupedArray = _.chain(list)
                       .groupBy(function (x) { return x.duedate })
                       .map(function (value, date) { 
                           return {
                               duedate: date,
                               myValues: value
                           };
                       })
                       .value();

JS Fiddle: http://jsfiddle.net/t2tCa/

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

1 Comment

Glad to help. This was actually a fun one!

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.