Comparing two arrays and adding objects to the other one

Viewed 87

I have two arrays:

let array1 = [
  {
    _id: '5eaf8eeac436dbc9b7d75f35',
    name: 'Strawberry',
    category: 'organic',
    image: '/productImages/australian.jpg',
    price: '9.65',
    quantity: 1
  },
  {
    _id: '5eaf8f61c436dbc9b7d75f36',
    name: 'Organic Wild Blue Berry',
    category: 'organic',
    image: '/productImages/owbb.jpg',
    price: '12.50',
    quantity: 1
  },
  {
    _id: '5eb0ac47d98c817d9a82df82',
    name: 'Mango',
    category: 'australian',
    image: '/productImages/australian.jpg',
    price: '12.25',
    quantity: 1
  },
  {
    _id: '5eb0ac71d98c817d9a82df83',
    name: 'Peas',
    category: 'conventional',
    image: '/productImages/owbb.jpg',
    price: '25.12',
    quantity: 1
  }
]

let array2 = [
  {
    _id: '5ec00539f7ff70566fd8a557',
    productid: {
      _id: '5eaf8eeac436dbc9b7d75f35',
      name: 'Strawberry',
      category: 'organic',
      image: '/productImages/australian.jpg',
      price: '9.65'
    },
    quantity: 3
  },
  {
    _id: '5ec00539f7ff70566fd8a558',
    productid: {
      _id: '5eaf8f61c436dbc9b7d75f36',
      name: 'Organic Wild Blue Berry',
      category: 'organic',
      image: '/productImages/owbb.jpg',
      price: '12.50'
    },
    quantity: 3
  }
]

I need to check if productId of array2 matches any object _id of array1. If so, I need to add each object's quantities to one another. Otherwise, I need to push one to another.

For example, if "_id": "5eb0ac71d98c817d9a82df83" doesn't exist in any object of array2's productId, push it into array2. And if any element of array2 doesn't exist in array1, push it into array1.

I managed to update the quantity if one of the objects included in the other array but can't figure out a way to push the rest of the objects to one another.

Here is how I combined the quantities of matching _id from array1 to productId in array2

if (array1.length > 0) {
  for (let i = 0; i < array2.length; i++) {
    for (let k = 0; k < array1.length; k++) {
      if (array2[i].productid._id === array1[k]._id) {
        array1[k].quantity = array1[k].quantity + array2[i].quantity
        array2[i].quantity = array1[k].quantity
      }
    }
  }
}

Expected result based on example above:

array1 = [
  {
    _id: '5eaf8eeac436dbc9b7d75f35',
    name: 'Strawberry',
    category: 'organic',
    image: '/productImages/australian.jpg',
    price: '9.65',
    quantity: 4
  },
  {
    _id: '5eaf8f61c436dbc9b7d75f36',
    name: 'Organic Wild Blue Berry',
    category: 'organic',
    image: '/productImages/owbb.jpg',
    price: '12.50',
    quantity: 4
  },
  {
    _id: '5eb0ac47d98c817d9a82df82',
    name: 'Mango',
    category: 'australian',
    image: '/productImages/australian.jpg',
    price: '12.25',
    quantity: 1
  },
  {
    _id: '5eb0ac71d98c817d9a82df83',
    name: 'Peas',
    category: 'conventional',
    image: '/productImages/owbb.jpg',
    price: '25.12',
    quantity: 1
  }
]

array2 = [
  {
    _id: '5ec00539f7ff70566fd8a557',
    productid: {
      _id: '5eaf8eeac436dbc9b7d75f35',
      name: 'Strawberry',
      category: 'organic',
      image: '/productImages/australian.jpg',
      price: '9.65'
    },
    quantity: 4
  },
  {
    _id: '5ec00539f7ff70566fd8a558',
    productid: {
      _id: '5eaf8f61c436dbc9b7d75f36',
      name: 'Organic Wild Blue Berry',
      category: 'organic',
      image: '/productImages/owbb.jpg',
      price: '12.50'
    },
    quantity: 4
  },
  {
    _id: 'auto-generated-id',
    productid: {
      _id: '5eb0ac47d98c817d9a82df82',
      name: 'Mango',
      category: 'australian',
      image: '/productImages/australian.jpg',
      price: '12.25'
    },
    quantity: 1
  },
  {
    _id: 'auto-generated-id',
    productid: {
      _id: '5eb0ac71d98c817d9a82df83',
      name: 'Peas',
      category: 'conventional',
      image: '/productImages/owbb.jpg',
      price: '25.12'
    },
    quantity: 1
  }
]
3 Answers

You can do this with reduce function. Here is my try:

var array1 =[{"_id":"5eaf8eeac436dbc9b7d75f35","name":"Strawberry","category":"organic","image":"/productImages/australian.jpg","price":"9.65","quantity":1},{"_id":"5eaf8f61c436dbc9b7d75f36","name":"Organic Wild Blue Berry","category":"organic","image":"/productImages/owbb.jpg","price":"12.50","quantity":1},{"_id":"5eb0ac47d98c817d9a82df82","name":"Mango","category":"australian","image":"/productImages/australian.jpg","price":"12.25","quantity":1},{"_id":"5eb0ac71d98c817d9a82df83","name":"Peas","category":"conventional","image":"/productImages/owbb.jpg","price":"25.12","quantity":1}];

var array2=[ { _id: '5ec00539f7ff70566fd8a557', productid: { _id: '5eaf8eeac436dbc9b7d75f35', name: 'Strawberry', category: 'organic', image: '/productImages/australian.jpg', price: '9.65', }, quantity: 3 }, { _id: '5ec00539f7ff70566fd8a558', productid: { _id: '5eaf8f61c436dbc9b7d75f36', name: 'Organic Wild Blue Berry', category: 'organic', image: '/productImages/owbb.jpg', price: '12.50', }, quantity: 3 }];


result = array1.reduce((acc, elem, i)=>{
    index = array2.findIndex(val=>val.productid._id == elem._id);
 if(index!=-1) {
  array2[index].quantity = elem.quantity += array2[index].quantity;
 } else {
   array2.push({_id:'some_id'+i, productid: elem, quantity: elem.quantity})
 }
    acc.push(elem);
 return acc;
},[]);

result = [...result, ...array2.filter(elem=> !array1.some(val=>val._id == elem.productid._id)).map(({productid, quantity})=>({...productid, quantity}))];


console.log(result);
console.log(array2)

I would add the quantities of the first array to the second, then regenerate the second array based on the first:

  // Create a lookup table to make the whole thing O(n)
  const entryById = {};
  for(const item of array2)
    entryById[item.productid._id] = item;

  // Update array2 with the amount of array1
  for(const item of array1) {
    if(entryById[item]) {
       entryById[item].amount += item.amount;
    } else {
       array2.push(entryById[item] = {
         _id: 'generated',
         productid: item,
         amount: item.amount,
      });
    }
  }

 // Regenerate array1
 array1 = array2.map(({ productid, amount }) => ({ ...productid, amount }));

I find it strange though that you maintain two different datastructures here.

You could take a hash table for the second array and iterate the first and push a new data set and update the values.

let array1 = [{ _id: "5eaf8eeac436dbc9b7d75f35", name: "Strawberry", category: "organic", image: "/productImages/australian.jpg", price: "9.65", quantity: 1 }, { _id: "5eaf8f61c436dbc9b7d75f36", name: "Organic Wild Blue Berry", category: "organic", image: "/productImages/owbb.jpg", price: "12.50", quantity: 1 }, { _id: "5eb0ac47d98c817d9a82df82", name: "Mango", category: "australian", image: "/productImages/australian.jpg", price: "12.25", quantity: 1 }, { _id: "5eb0ac71d98c817d9a82df83", name: "Peas", category: "conventional", image: "/productImages/owbb.jpg", price: "25.12", quantity: 1 }],
    array2 = [{ _id: '5ec00539f7ff70566fd8a557', productid: { _id: '5eaf8eeac436dbc9b7d75f35', name: 'Strawberry', category: 'organic', image: '/productImages/australian.jpg', price: '9.65', }, quantity: 3 }, { _id: '5ec00539f7ff70566fd8a558', productid: { _id: '5eaf8f61c436dbc9b7d75f36', name: 'Organic Wild Blue Berry', category: 'organic', image: '/productImages/owbb.jpg', price: '12.50', }, quantity: 3 }],
    ids = array2.reduce((r, o) => {
        r[o.productid._id] = o; return r;
    }, {}),
    result = array1.forEach(o => {
        if (ids[o._id]) {
            const value = o.quantity;
            o.quantity += ids[o._id].quantity;
            ids[o._id].quantity += value;
        } else {
            const { quantity, ...productid } = o;
            array2.push(ids[productid._id] = { _id: 'auto-generated-id', productid, quantity });
        }
    });

   console.log(array1);
   console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related