Compare 2 different Arrays by ID and calculate difference

穿精又带淫゛_ 提交于 2021-02-11 17:51:31

问题


I got 2 arrays

ArrayA = {"data":{"PlayerList":[{"Platform":1,"PlayerExternalId":205288,"Price":250,"RemainingTime":22},{"Platform":1,"PlayerExternalId":205753,"Price":10000,"RemainingTime":22}]}}

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

ArrayB is like a small database to compare prices. ArrayA needs theoretically an Interception with ArrayB. But this creates a new ArrayC which is complicated for me because I need the index of the results from ArrayA.

Moreover when comparing both array IDs, I need to compare both prices and calculate a difference into a variable so I can work with it later. How can I achieve this?

This is my pseudo code. Idk if this is even the right way..

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

Edit: or could I append the price from arrayB to arrayA and can calculate then somehow?


回答1:


You can pass both arrays to following function: I have stored index, now if you only need index, you don't need to sort it otherwise I am sorting it on the base of index to keep the original order.

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


来源:https://stackoverflow.com/questions/61528389/compare-2-different-arrays-by-id-and-calculate-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!