Home > other >  how to decrease the values ​of array1 in relation to array2 in javascript
how to decrease the values ​of array1 in relation to array2 in javascript

Time:04-08

I'm trying to create a function to compare two arrays by position [2] of each array and make one array minus the other, but I'm having a problem with the final result, which should be:

var ar1 = [['x123', '10', 'AA'],['x123', '20', 'BB'],['x123', '30', 'CC']]
var ar2 = [['x123', '12', 'CC'],['x123', '2', 'B1'],['x123', '2', 'CC'], ['x123', '2', 'BB']]

 var t = ar1.map(a => {
     var x = ar2.filter( b => b[2] == a[2])
     if( x.length > 0 ){
         return [a[0], a[1] - x[0][1], a[2]]
     } else {
         return a
     }

 })

console.log(t)

//the end result I would like

 ['x123', 8, 'B1']
 ['x123', 18, 'BB']
 ['x123', 6, 'CC']

CodePudding user response:

I think this is what you're looking for, although your example and expected output don't quite match:

const ar1 = [['x123', '10', 'AA'],['x123', '20', 'BB'],['x123', '30', 'CC']];
const ar2 = [['x123', '12', 'CC'],['x123', '2', 'B1'],['x123', '2', 'CC'], ['x123', '2', 'BB']];

 const t = ar1.map(a => {
     const x = ar2.filter(b => b[2] == a[2]);
     if (x.length > 0){
        const sum = x.reduce((prev, cur) => prev   Number(cur[1]), 0);
        return [a[0], a[1] - sum, a[2]];
     } else {
        return a;
     }
 })

console.log(t);

CodePudding user response:

too much code here but i got the same result

/*  
var ar1 = [['A', '10', 'B1'],['B', '20', 'BB'],['C', '20', 'CC']]
var ar2 = [['C', '12', 'CC'],['B', '2', 'B1'],['C', '2', 'CC'], ['B', '2', 'BB']]
*/
var ar1 = [['x123', '10', 'AA'],['x123', '20', 'BB'],['x123', '30', 'CC']];
var ar2 = [['x123', '12', 'CC'],['x123', '2', 'B1'],['x123', '2', 'CC'], ['x123', '2', 'BB']];


//PREPARE ar2 :

tmp=[];
ar2.map(a2 => {

    ch=a2[0] a2[2];//VIRTUAL KEY    
    vl=parseInt(a2[1]);

    /*
    if(tmp[ch]===undefined){
        
        tmp[ch]=vl;
        
    }else{
        
        tmp[ch]=tmp[ch] vl;
        
    }*/
    tmp[ch]=(tmp[ch]===undefined?vl:tmp[ch] vl);

});

solution=[];
ar1.map(a1 => {
    ch=a1[0] a1[2];//VIRTUAL target KEY
    solution.push([a1[0],a1[1]-(tmp[ch]!==undefined?tmp[ch]:0),a1[2] ]);

});





console.log(solution);

  • Related