Compare multiple arrays

1

I have two arrays, which are:

data [  
   0{  
     nome: a
     numero: 2
    }  
   1{
     nome: b
     numero: 3 
    }
   2{
     nome: b
     numero: 3 
    }
   3{
     nome: b
     numero: 8
    }
]  

dataNota[    
   0{    
     nf: 9999  
     numero: 2    
    }    
   1{  
     nf: 2000   
     numero: 3    
    }  
   2{  
     nf: 1000  
     numero: 5    
    }  
]    

I need to generate a new array containing the information where my id would be the "number" field in both the data and date arrays.

I'm doing the following for:

for(var x=0; x<data.length; x++){    
  for (var y=0; y<dataNota.length; y++){  
   if(data[x].numero == dataNota[y].numero){
    conf[x][0] = data[x].numero;
    conf[x][1] = dataNota[y].nf;
   }else{
    conf[x][0]="";
   }
  }
} 
var excel = nodeExcel.execute(conf);  
res.setHeader('Content-Type', 'application/vnd.openxmlformats');
res.setHeader("Content-Disposition", "attachment; filename=" + "Teste.xlsx");
res.end(excel, 'binary');

However, whenever you find an equal number in both arrays, it fills only one of the values, never all, and the name fills in for all.

I would like to do it another way, maybe using a each, because my problem is in the for. Any suggestions?

    
asked by anonymous 03.05.2016 / 22:05

1 answer

2

The simplest is to make an object that has the key "id" you want to use, that is what these arrays have in common, the key number .

This could be done like this:

function misturar(obj, referencia) {
    if (!obj) return;
    var id = obj.numero;
    if (!referencia[id]) referencia[id] = {};
    for (var prop in obj) {
        referencia[id][prop] = obj[prop];
    }
}

var dados = {};
var length = Math.max(data.length, dataNota.length);
for (var i = 0; i < length; i++) {
    misturar(data[i], dados);
    misturar(dataNota[i], dados);
}
console.log(JSON.stringify(dados));

and the result would be:

{
    "2": {
        "nome": "a",
        "numero": 2,
        "nf": 9999
    },
    "3": {
        "nome": "c",
        "numero": 3,
        "nf": 2000
    },
    "5": {
        "nf": 1000,
        "numero": 5
    },
    "8": {
        "nome": "d",
        "numero": 8
    }
}

jsFiddle: link

    
20.05.2016 / 00:03