midhun k midhun k - 5 months ago 9
Node.js Question

merging two arrays in nodejs

This function will returns an array containing shop details and images.

function listshops(callback)
{
var array=[3,4];
async.each(array,function(dat,callback){

async.parallel([

function(callback){
c function listshops(callback)
{
var array=[3,4];/*shopId*/
async.each(array,function(dat,callback){

async.parallel([

function(callback){
client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
callback(null,data1);

});
},

function (callback) {
client.connection.query('select * from image where shopId=?',dat,function(err,data2){
callback(null,data2);

});
}
],
function(err,data)
{
console.log(data);

});
});

}


The output for above code is:: http://i.stack.imgur.com/laxf8.png

I need to merge the array containing shop information and images into single array.That is shop information with corresponding images.

[
{ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 },
{ imageId: 1, shopId: 3, imageUrl: 'aaa' },
{ imageId: 2, shopId: 3, imageUrl: 'bbb' }
]

Answer

You could flatten the array using reduce: [[1],[2]] --> [1,2]

var array = [[1,2],[3]];
array.reduce(function(prev, curr) {
  return prev.concat(curr);
});

In your case:

  function listshops(callback)
    {   
     var array=[3,4];/*shopId*/
      async.each(array,function(dat,callback){

         async.parallel([

             function(callback){
                client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
                callback(null,data1);

               });
            },       

             function (callback) {
                client.connection.query('select * from image where shopId=?',dat,function(err,data2){
                callback(null,data2);

               });
            }
         ],
         function(err,data)
         {
            var result = data.reduce(function(prev, curr) {
              return prev.concat(curr);
            });
            console.log(result);
         });
     });

    }