Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate uniques after subtracting arrays' elements based on conditions using JS?

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()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)]));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading