88986

Comparing two arrays and adding objects to the other one

<h3>Question</h3>

I have two arrays:

<pre class="lang-js prettyprint-override">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

<pre class="lang-js prettyprint-override">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:

<pre class="lang-js prettyprint-override">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 } ]
<h3>Answer1:</h3>

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

<pre class="snippet-code-js lang-js prettyprint-override">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)
<h3>Answer2:</h3>

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.


<h3>Answer3:</h3>

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

<pre class="snippet-code-js lang-js prettyprint-override">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); <pre class="snippet-code-css lang-css prettyprint-override">.as-console-wrapper { max-height: 100% !important; top: 0; }

来源:https://stackoverflow.com/questions/61840455/comparing-two-arrays-and-adding-objects-to-the-other-one

Recommend

  • Set hibernate dialect for jpa in YML
  • Reshape a pandas DataFrame of (720, 720) into (518400, ) 2D into 1D
  • Get scaffolder to generate fields in specific order
  • how to find record insert to mysql using commit()
  • What could be causing the primary key exception?
  • chrome extension with service worker receiving push notifications
  • How to make a 1D lut in C++ for GLSL
  • How to only load certain fields of a child object in Entity Framework 6.1?
  • Dex error when trying to build ionic Android app
  • disable Tensorflow eager execution
  • Why am I getting compile error “use of deleted function 'std::unique_ptr …”
  • How to write the scripts for Qt Installer
  • How many pixels are scrolled on a website with a mouse wheel down event?
  • Is there a modern ( e.g. CLR ) replacement for bison / yacc?
  • overriding equals and hashcode methods in java?
  • Simulating argparse command line arguments input while debugging
  • Why is this Animatable property being set again?
  • Max execution time error
  • What is need of Assign/Deassign in Verilog?
  • Winston logger not write to file
  • How exactly do you use json_decode to pass a javascript array to php?
  • How to sort by Lucene.Net field and ignore common stop words such as 'a' and 'the
  • Why am I getting an Argument exception when creating event handler dynamically?
  • ASP.NET GridView throws: The version of SQL Server in use does not support datatype 'date'
  • How to process remote XML files with XSLT
  • How to add html image in to velocity template file to send email?
  • How to define something in JavaScript [closed]
  • Amazon Elastick BeanStalk error: Failed to create the AWS Elastic Beanstalk application version
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • How to decleare char *const argv[] in swift [duplicate]
  • Send array to next viewcontroller iOs xcode [duplicate]
  • Comma decimal separator is ignored by ASP.NET MVC model binder
  • Grails - How to implement a foreign key relationship not using an id column?
  • Cross compile glibc for arm, got undefined reference to some unwind functions
  • Running R's aov() mixed effects model from Python using rpy2
  • JavaScript RegExp Replace