簡體   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