0

I have the following array format:

var myArr = [
{
    "a": "1",
    "b": "2",
    "c": "3",
    "d" {
        "0" : "1",
        "1" : "2"
    },
    "blah" : "me"
},
{
    "a": "5",
    "b": "3",
    "c": "1",
    "d" {
        "0" : "6",
        "1" : "3"
    },
    "blah" : "me"
},
{
    "a": "5",
    "b": "3",
    "c": "1",
    "d" {
        "0" : "6",
        "1" : "3"
    },
    "blah" : "you"
}
]

I am wondering how I could map a new array such that the values under "blah" are together like

var myArr = [{
    "me" : [
    {
        "a": "1",
        "b": "2",
        "c": "3",
        "d": {
            "0" : "1",
            "1" : "2"
            }
    },
    {
        "a": "5",
        "b": "3",
        "c": "1",
        "d": {
            "0" : "6",
            "1" : "3"
            }
    }
    ],
    "you" : [
    {
        "a": "5",
        "b": "3",
        "c": "1",
        "d": {
            "0" : "6",
            "1" : "3"
            }
    }
    ]
}]
1
  • @jbabey - well wasn't sure where to start :( so need some help pretty much Commented Jan 28, 2013 at 14:13

1 Answer 1

1

That's very possible, try this:

var output = {};
myArr.forEach(function(elem){     // Loop trough the elements in `myArr`
    if(!output[elem.blah]){       // If the output object doesn't have a property named by elem.blah, yet
        output[elem.blah] = [];   // Create a empty array
    }
    output[elem.blah].push(elem); // Push the current element to that array
    delete elem.blah;             // And delete the mention of `blah` from it (optional)
});

Instead of forEach, you can also use a normal for loop, for more compatibility:

var output = {};
for(var i = 0; i < myArr.length; i++){ // Loop trough the elements in `myArr`
    var elem = myArr[i];
    if(!output[elem.blah]){            // If the output object doesn't have a property named by elem.blah, yet
        output[elem.blah] = [];        // Create a empty array
    }
    output[elem.blah].push(elem);      // Push the current element to that array
    delete elem.blah;                  // And delete the mention of `blah` from it (optional)
});

With underscore.js, you can just do this:

_.groupBy(myArr, 'blah');

the only difference is that this won't remove the blah property from the source objects.

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

2 Comments

wow great thanks! i am using underscore if thats helps in anyway :) otherwise thanks heaps
Oh, that simplifies matters. With underscore.js, you can just do this: _.groupBy(myArr, 'blah')

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.