我的阵列有问题。我想将不同的数组合并在一起。不同的数组可能不止于此。我将在下面显示我的收藏。
let myCollection = [
{
_id: '0003',
avgCost: 10,
itemId: '0003',
onHand: 12,
inventoriesValue: 120,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 12,
inventoriesValue: 240,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 10,
inventoriesValue: 200,
}
]
我想通过itemId组合元素以实现以下结果。
[
{
_id: '0003',
avgCost: 10,
itemId: '0003',
onHand: 12,
inventoriesValue: 120,
},
{
_id: '0001',
avgCost: 20,
itemId: '0001',
onHand: 22,
inventoriesValue: 440,
},
]
答案 0 :(得分:0)
如果我理解这个问题,则您正在尝试对两个数组执行并集操作,但需要进行对象比较。有几种方法可以做到这一点。
如果您使用的是from timeit import default_timer as timer
from numba import jit
def DumbPrimeFactors(n):
result_list = list()
prime = 2
remaining = n
while remaining > 1:
if remaining % prime == 0:
result_list.append(prime)
remaining /= prime
prime -= 1
prime +=1
return result_list
start = timer()
print(DumbPrimeFactors(500000000008))
print(f"time: {timer() - start}")
start = timer()
SmartPrimeFactors = jit(DumbPrimeFactors)
print(SmartPrimeFactors(500000000008))
print(f"time: {timer() - start}")
,则可以使用两个数组执行以下操作:
lodash
或者,如果您有一个数组数组,则可以执行以下操作:
_.unionWith(arr1, arr2, _.isEqual);
答案 1 :(得分:0)
基本上,您需要创建一个新数组,该数组将原始数组中的所有相同元素相加。以下代码适用于小型数组。
many-to-many
请注意,这假设每个元素中的const targetArray = []; // an empty array for the results
myCollection.forEach(mc => { // loop over the original array
let i = targetArray.findIndex(ta => ta.itemId == mc.itemId); // match on itemId
if (i > -1) { // found a match
targetArray[i].onHand += mc.onHand; // increment the onHand value
targetArray[i].inventoriesValue += mc.inventoriesValue; // and inventoriesValue
} else { // no match found
targetArray.push(mc); // push the element
}
});
是相同的。如果它们不同,则需要根据要添加的新库存进行加权平均。