javascript - 通过 ID 比较 2 个不同的数组并计算差异

标签 javascript arrays

我有2个数组

ArrayA = {"data":{"PlayerList":[{"Platform":1,"PlayerExternalId":205288,"Price":250,"RemainingTime":22 },{"平台":1,"PlayerExternalId":205753,"价格":10000,"剩余时间":22}]}}

ArrayB = {"datafut": [{"currentPricePs4": "4149000","currentPriceXbox": "3328000","PlayerExternalId": "151152967"},{"currentPricePs4 ": "3315000","currentPriceXbox": "2720000","PlayerExternalId": "151198320"}]}

ArrayB就像一个用于比较价格的小型数据库。 ArrayA 理论上需要 Interception与数组B。但这会创建一个新的 ArrayC,这对我来说很复杂,因为我需要 ArrayA 结果的索引。

此外,在比较两个数组 ID 时,我需要比较两个价格并将差异计算到变量中,以便稍后使用。我怎样才能实现这个目标?

这是我的伪代码。我不知道这是否是正确的方法..

Filter ArrayB by ArrayA //by playerID
for(
NewPrice = ArrayA.price / ArrayB.price + Index of ArrayA.price
index = Index of ArrayA.price)

编辑:或者我可以将价格从 arrayB 附加到 arrayA 并可以以某种方式计算吗?

最佳答案

您可以将两个数组传递给以下函数:我已经存储了索引,现在如果您只需要索引,则不需要对其进行排序,否则我将根据索引对其进行排序以保持原始顺序。

function mergeArrays(arrayA, arrayB) {

    var players = arrayA.data.PlayerList;
    var data = arrayB.data;
    var arrayC = [];

    for(let i=0; i<data.length; i++) {  
        var playerId = data[i].PlayerExternalId;
        for(let j=0; j<players.length; j++) {
            if(players[j].PlayerExternalId != playerId) {
                continue;
            }
            var obj = {};
            obj.playerId = playerId;
            obj.index = j;
            obj.price = players[j].price;
            obj.xboxprice = data[i].currentPriceXbox;
            obj.ps4price = data[i].currentPricePs4;
            arrayC.push(obj);
        }
    }
    arrayC.sort((a,b) => (a.index < b.index)?-1:(a.index>b.index?1:0));
    return arrayC;
}

关于javascript - 通过 ID 比较 2 个不同的数组并计算差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528389/

相关文章:

javascript - 检索 xml 文件中的值并在 Javascript 的另一个函数中使用它

javascript - 我需要对用户输入名称 Javascript 的数组顺序进行排序

javascript - javascript中函数的替代方法

C 在数组中添加和搜索已解析的数据

c++ - 创建对整数数组指针的 vector<int> 引用 (C++)

javascript - 在 JavaScript 中判断两个时区是否相同

javascript - 为什么这个简单的电子邮件验证不执行?

javascript - 仅替换 Javascript 中的最后一个数字

javascript - 为什么在 HTML 中,允许按钮调用函数而不将按钮包装在 SCRIPT 标记中?

arrays - Powershell-调用每个对象的函数会更改所有对象中的数组时的奇怪行为