1

I have an multidimensional array with objects in it..How can I flatten it

myarr[0] =[{"name":"john","age":"50","location":"san diego"}
           ,{"name":"jane","age":"25","location":"new york"}
           ,{"name":"susane","age":"10","location":"los angeles"}     
               ];
myarr[1] =[{"smoker":"yes","drinker":"no","insured":"no"}
           ,{"smoker":"no","drinker":"no","insured":"yes"}
           ,{"smoker":"no","drinker":"yes","insured":"no"}     
               ];
myarr[1] =[{"status":"married","children":"none"}
           ,{"status":"unmarried","children":"one"}
           ,{"status":"unmarried","children":"two"}     
               ];
2
  • flatten means to flatten a multidimensional array --make one dimensional array of it--I mean, sorry for confusion. eg would my array containing all the objects in ascending order. Commented Oct 28, 2011 at 4:08
  • Check out concat here. Commented Oct 28, 2011 at 4:10

1 Answer 1

2

I think this is what you're trying to do.

First you want a simple helper function to merge two objects:

function merge(a, b) {
    a = a || { };
    for(var k in b)
        if(b.hasOwnProperty(k))
            a[k] = b[k];
    return a;
}

Then you can just loop through your array of arrays to merge the objects:

var flat = [ ];
for(var i = 0; i < myarr.length; ++i)
    for(var j = 0; j < myarr[i].length; ++j)
        flat[j] = merge(flat[j], myarr[i][j]);

And then sort it:

flat.sort(function(a, b) {
    a = a.location;
    b = b.location;
    if(a < b)
        return -1;
    if(a > b)
        return 1;
    return 0;
});

Demo (run with your JavaScript console open): http://jsfiddle.net/ambiguous/twpUF/

References:

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

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.