Compare multiple arrays

Asked

Viewed 184 times

1

I have two arrays, being them:

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 date and date arrays.

Here’s what I’m doing:

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 he finds an equal number in the two arrays, he fills only one of the values, never all, already the name he fills for all.

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

1 answer

2


The simplest is to make an Object that has as key that "id" you want to use, or whatever these arrays have in common, the key number.

This could be done:

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: https://jsfiddle.net/rqx8c4t2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.