在对象数组中的字符串中查找数值并进行计算

时间:2019-06-11 07:25:20

标签: javascript reactjs

我的JavaScript数组如下。

:archive

我需要选择以下详细信息:

[ 
{id:1, msg:"Your Acct 123XXXX456 Has Been Debited with USD2,100.00 On 05- 
MAY- 2019 07:26:58 By AB: 123456**7899/USER NAME/0505201. Bal: 
USD973.28CR"}, <br/>
{id:1, msg: "Your Acct 123XXXX456 Has Been Debited with USD1,100.00 On 
05-MAY-2019 07:26:58 By AB: 123456**7899/USER NAME/0505201. Bal: 
USD673.28CR"},<br/>
{id:2, msg: "Your Acct 345XXXX678 Has Been Debited with USD4,100.00 On 
05-MAY-2019 07:26:58 By AB: 11111**22222/USER NAME/0505201. Bal: 
USD373.28CR"}
]

我尝试了以下方法从字符串中获取非数字。

(1) Highest Debit amount (for particular user)
(2) Lowest Debit amount (for particular user)
(3) Sum all the debit amount for particular user.

但是输出是这样的。

let result = myArr[0].replace(/\D+/g, ' ').trim().split(' ').map(e => 
parseInt(e));

这种方法是将逗号放在每个数字的前面,删除前面的00的小数点。我不知道如何只选择借方金额。 我期望这样的输出:

[123,456,2,1,00,5]

User   Highest Debit    Lowest Debit   Total Debit 
 1       2,100.00         1,100.00       3,200.00 
 2       4,100.00         4,100.00       4,100.00 

1 个答案:

答案 0 :(得分:2)

您的正则表达式太简单了

这是使用Math.min和Math.max每次取款的一种方法

我当时正在考虑使用reduce,但这更具可读性

myArr = [
  { "id": 1, "msg": "Your Acct 123XXXX456 Has Been Debited with USD2,100.45 On 05 - MAY - 2019 07: 26: 58 By AB: 123456 ** 7899 / USER NAME / 0505201. Bal: USD973 .28 CR " },
  { "id": 1, "msg": "Your Acct 123XXXX456 Has Been Debited with USD1,100.50 On 05 - MAY - 2019 07: 26: 58 By AB: 123456 ** 7899 / USER NAME / 0505201. Bal: USD673 .28 CR " },
  { "id": 2, "msg": "Your Acct 345XXXX678 Has Been Debited with USD4,100.00 On 05 - MAY - 2019 07: 26: 58 By AB: 11111 ** 22222 / USER NAME / 0505201. Bal: USD373 .28 CR "}
]

let res = {}
myArr.forEach(obj => {
    const id  = obj.id;
    const msg = obj.msg;
    const uPos = msg.indexOf("USD"); // assuming a static message
    // grab the amount, use + to convert to number after removing the thousand separator
    const num = +msg.substring(uPos+3,msg.indexOf(" ",uPos)).replace(/,/g,"")
    let cur = res[id];
    if (!cur) { res[id]={}; cur=res[id]; cur.total=0;}
    cur.low  =  cur.low  ?  Math.min(cur.low, num) : num;
    cur.high =  cur.high ?  Math.max(cur.high,num) : num;
    cur.total += num;
})
console.log(res);