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.

Cheruiyot Felix
  • 1,397
  • 4
  • 21
  • 37
  • http://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays-in-javascript – Zhihao Jan 21 '14 at 15:15
  • 1
    You mean { task : 2 } etc. right ? – tomdemuyt Jan 21 '14 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. – Cheruiyot Felix Jan 21 '14 at 15:33

4 Answers4

1

You can use join()

A good starting point:

array[0] = array[0].join(", ");
RyanS
  • 3,455
  • 1
  • 21
  • 36
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 
}
Ali
  • 473
  • 2
  • 7
  • Doesn't underscore have a flatten method? – Dexygen Jan 22 '14 at 20:16
  • 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. – Ali Jan 22 '14 at 20:39
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.

roland
  • 7,135
  • 6
  • 42
  • 60
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

RIYAJ KHAN
  • 13,830
  • 5
  • 27
  • 48