1

How can one flatten this in javascript?

[
    [ task: 2 ],
    [ status: 'REFUND' ],
    [],
    [ amount: 872.2 ] 
]

To something like:

[task: 2, status: 'REFUND', amount: 872.2]

Tried several options including Array.prototype.reduce() but did not work for me.

3
  • stackoverflow.com/questions/10865025/… Commented Jan 21, 2014 at 15:15
  • 1
    You mean { task : 2 } etc. right ? Commented Jan 21, 2014 at 15:15
  • No tomdemuyt. I get above from an array.push(), like this: var a = []; var b = []; var c = []; a[task] = 2; b[status] = 'REFUND'; c.push(a) c.push(b) For some reason I cannot put them in one variable. They come from different functions. Commented Jan 21, 2014 at 15:33

4 Answers 4

1

You can use join()

A good starting point:

array[0] = array[0].join(", ");
Sign up to request clarification or add additional context in comments.

Comments

1

you can use underscore.js

var u = require('underscore');
u.reduce(a, function(memo, item) { 
    var o = {}; 
    u.each(memo, function(v, k) { 
        o[k] = v; 
    }); 
    u.each(item, function(v, k) { 
        o[k] = v; 
    }); 
    return o;
});


Input:

[
    { task: 2 },
    { status: 'REFUND' },
    {},
    { amount: 872.2 }
]

Output:

{ 
   task: 2,
   status: 'REFUND',
   amount: 872.2 
}

2 Comments

Doesn't underscore have a flatten method?
Underscore does have a flatten method. But you cannot use it in this case. It would have worked if it was an array of an array. But since its an array of an object _.flatten would return the input itself.
0

Your syntax is invalid; there is no : allowed outside of an object literal.

var arr = [
  [{task: 2}],[{status: 'REFUND'}],[],[{amount: 872.2}]
];

To flatten your array, use the versatile reduce:

var result = arr.reduce(function(a,b) {
  return a.concat(b)
}); //result.length === 3

Your result contains 3 elements as [] is filter out

reduce is part of ECMAScript 5th edition. Ensure your browser supports it.

Comments

0

Please check this one.

var a = [], b = [],c = [],d=[]; 
 a['task'] = 2;
 b['status'] = 'REFUND';
 d['amount']= 872.2

 c.push(a); 
 c.push(b);
 c.push(d) 
 var arr = [];
console.log(c)

for(var key in c){
    //console.log(Object.keys(c[key]),c[key][Object.keys(c[key])]);
     arr[Object.keys(c[key])]=c[key][Object.keys(c[key])];
   }

 console.log(arr)  // please see the console.

Here is the plunker

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.