通过ID比较2个不同的数组并计算差异 [英] Compare 2 different Arrays by ID and calculate difference
问题描述
我有2个数组
ArrayA = <代码> {数据":{"PlayerList":[{平台":1,"PlayerExternalId":205288,价格":250,剩余时间":22},{"Platform":1,"PlayerExternalId":205753,"Price":10000,"RemainingTime":22}]}}
ArrayB = <代码> {"datafut":[{"currentPricePs4":"4149000","currentPriceXbox":"3328000","PlayerExternalId":"151152967"}},{"currentPricePs4:" 3315000," currentPriceXbox:" 2720000," PlayerExternalId:" 151198320}}}
ArrayB就像一个比较价格的小型数据库.从理论上讲,ArrayA需要通过ArrayB 拦截.但这会创建一个新的ArrayC,这对我来说很复杂,因为我需要ArrayA的结果索引.
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.
此外,在比较两个数组ID时,我需要比较两个价格并将差异计算为变量,以便以后使用.我该如何实现?
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)
或者我可以将价格从arrayB追加到arrayA并可以通过某种方式进行计算吗?
or could I append the price from arrayB to arrayA and can calculate then somehow?
推荐答案
您可以将两个数组都传递给以下函数:我已经存储了索引,现在如果只需要索引,则不需要对其进行排序,否则我将进行排序它以索引为基础来保持原始顺序.
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;
}
这篇关于通过ID比较2个不同的数组并计算差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!