How to check if the item in array1
exists in array2
and, if so, subtract col4 from col5 to output th pending qty. If not, then, item's qty from array1
is the pending qty.
let array1 =
[
[1, "Item A", "Food", 10, 0],
[2, "Item B", "Food", 5, 0],
[3, "Item C", "Food", 30, 0]
]
let array2 =
[
[1, "Item A", "Food", 5, 3],
[3, "Item C", "Food", 10, 5]
]
Expected Result
let res=
[
[1, "Item A", "Food", 10, 7],
[2, "Item B", "Food", 5, 0],
[3, "Item C", "Food", 30, 25]
]
I started it using for
loops, but I was wondering what this would look like using map()
or reduce()
?
let array1 = [
[1, "Item A", "Food", 10, 0],
[2, "Item B", "Food", 5, 0],
[3, "Item C", "Food", 30, 0]
]
let array2 = [
[1, "Item A", "Food", 5, 3],
[3, "Item C", "Food", 10, 5]
]
let result = [];
for (let a = 0; a < array1.length; a ) {
let item = [];
for (let r = 0; r < array2.length; r ) {
if (array1[a][0] == array2[r][0] && array1[a][1] == array2[r][1]) {
let pendingQty = array1[a][3] - array2[r][4];
if (pendingQty > 0) {
item = [array1[a][0], array2[r][1], array2[r][2], array2[r][3], pendingQty];
} else {
item = array1[a];
}
}
if (item.length === 0) {
item = array1[a];
}
}
result.push(item.slice());
}
console.log(result)
Thanks
CodePudding user response:
let a1 = [ [1, "Item A", "Food", 10, 0], [2, "Item B", "Food", 5, 0], [3, "Item C", "Food", 30, 0]];
let a2 = [ [1, "Item A", "Food", 5, 3], [3, "Item C", "Food", 10, 5]];
console.log(a1.map(e=>[...e.slice(0,4),e[3]-(a2.find(j=>j[1]===e[1])?.[4]??0)]));