简体   繁体   中英

How to subtract value from one array to another and create a new Array?

I have 2 arrays A and B with the same length, and I would like to subtract ' balance ' and ' total ' from A to B and create a new array ' C ' with subtracted value....................................................................................

A = [
{
    "ID": 1,
    "balance": 100,
    "total": 1000,
    "date": "10/24/2019",
},
{
    "ID": 2,
    "balance": 200,
    "total": 2000,
    "date": "10/24/2019",
}
]

 B =[
{
    "ID": 1,
    "balance": 80,
    "total": 800,
    "date": "10/23/2019",
},
{
    "ID": 2,
    "balance": 90,
    "total": 900,
    "date": "10/23/2019",
}
]

New Array (A - B = C)

C = [
{
    "ID": 1,
    "balance": 20,
    "total": 200,
},
{
    "ID": 2,
    "balance": 110,
    "total": 1100,
}
]

The array contains objects

var C=[];
for (i=0;i<a.length;i++){
  result={};
  result.ID=A[i].ID;
  result.balance=A[i].balance-B[i].balance;
  result.total=A[i].total-B[i].total;//if it makes sense
  C.push(result);
}
console.log(C);

If you are certain of the length & position of the arrays you could iterate over the length of one of them:

const A = [];
const B = [];

const C = A.map((item, index) => ({
        ID: item.ID,
        balance: item.balance - B[index].total,
        total: item.total - B[index].total
    }))
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM