繁体   English   中英

如何将一个数组中的值减去另一个数组并创建一个新数组?

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

我有 2 个长度相同的 arrays AB ,我想从AB减去“余额”和“总计”,并创建一个新数组“ C ”,减去值............ ..................................................... ………………………………………………………………………………

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",
}
]

新阵列(A - B = C)

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

数组包含对象

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);

如果您确定 arrays 的长度和 position 您可以遍历其中一个的长度:

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
    }))
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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