score:0
Accepted answer
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)
score:0
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.
score:0
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; }
Source: stackoverflow.com
Related Query
- Comparing two arrays and adding objects to the other one
- Javascript 2 arrays of objects , get a value from one array of objects and assign it to the other array of objects
- A lookup function to match the same IDs in two different arrays of objects and inserting key/value pairs into one of the array of objects
- Comparing two arrays of nested objects and return new array of objects if compared values are not the same in javascript
- How to move two buttons one to the left and the other to the right in the same inline?
- Merging two arrays into one that has the same amount of objects
- Comparing two arrays and filtering one array upon this in javascript and react
- Accessing nested keys in object and compare them to other object keys, but the 2nd one is an array of objects
- On an HTML form with two buttons, how can I get one button to submit the form and the other one not?
- How do I map thorough the entire array which contains other objects and arrays as well in React?
- Comparing two array of objects and getting the difference
- How can I compare two arrays of objects and add new key to an objects in the second array
- Merge two arrays of different objects into one array of objects combined from the first two
- comparing name property on objects in two separate arrays and creating a new filtered array in React
- Compare the two arrays and replace/merge the values for id present in the other array (js)
- Typescript function parameter has two types, and the property of one type can't be accessed because it is not a property of the other type
- How to create and name two identical stateful components, where one uses Redux state and the other local state?
- Iterating over two arrays of objects and comparing data with same ID
- One to many relationship for MERN stack with two models model one is a movie and the other is a review model
- How do I compare two arrays of objects to see if they have the same ids and then return another value from the matching object?
- map two different arrays one within the other
- useState hook can only set one object at the time and return the other object of the same array to initial state
- React-Google-Maps displays two markers, one at the original position and another marker that follows the new center of the map onDrag
- Importing CSS in one component is adding CSS affect to other Components. How and Why?
- Align two elements on the same line using flex: one left and one right
- After editing only one field is edited and the other one behaves unexpectedly (React hooks)
- ReactJS - How to compare/filter matching id's of two arrays and use the result in a double search feature?
- How do I combine two arrays in react to get a new one with all of the items from the previous two?
- How would I compare two dates in a form and validate them? The second one shouldn't be before the first one
- Of two equal JSON objects, accessing values in javascript works in one case, the other returns undefined
More Query from same tag
- Can't update value of Office Fabric UI TextField in Enzyme test
- How to Add Array Values Mathematically
- React typescript Property 'map' does not exist on type 'User'
- Idiomatic way to handle Message Alerts state in React and Material-UI
- Passing function through useContext
- How do I import react-admin in a React Typescript appplication?
- React Data Grid external data update
- React.js: Toggle Buttons with children and parents
- How to only activate the onclick event of the top level button when having nested buttons? React.js
- Response from API returns data, state is undefined - React.JS
- Cannot install react-app because of a node version problem but I do have the last version installed
- Choose a random item based on probabilities
- How to apply a mutation using Formik?
- setState inside a Promise function in a useEffect with hooks?
- Axios api call returns not found error in reactjs
- Use ternary operator to change className in React
- How to combine document id and values in firestore
- Passing objects as props while retaining keys, using object map
- MUI : disable button conditional
- How to fix ''http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.'
- React.js and HTML5 email validation
- how to use icon in Ant-design/icons with V4
- 118:51: Expected to return a value at the end of arrow function array-callback-return
- Redux firing undefined action while using redux thunk
- Using Filter property of PrimeReact DataTable
- Cannot use connect function from react-redux
- react-query with rules of hook broken error
- How to stop the component from rendering before ajax call is completed in reactjs
- Warning: Find more than one child node with `children` in ResizeObserver. Will only observe first one
- change burger menu when click on link