I'm currently facing a challenge where I need to associate two arrays of objects, and I could really use some help with this. Explanation :
One array contains various reference products
const array1 = [
{name: peanuts, referenceKey: 0},
{name: almond, referenceKey: 1},
{name: nuts, referenceKey: 2},
{name: cream, referenceKey: 3}
]
The second array consists of open reference products with expiration dates and matching reference keys from array1
, along with specific keys for each open product
const array2 = [
{name: peanuts, expirationDate: "30d", referenceKey:0, otherKey: 42},
{name: peanuts, expirationDate: "20d", referenceKey:0, otherKey: 43},
{name: peanuts, expirationDate: "15h", referenceKey:0, otherKey: 44},
{name: almond, expirationDate: "30d", referenceKey:1, otherKey: 45},
{name: cream, expirationDate: "1d", referenceKey: 3, otherKey: 46},
{name:cream, expirationDate: "12h", referenceKey: 3, otherKey: 47}
]
My goal is to calculate the number of the same products in array2
that are open, and store this count in a new array
based on array1
, like so:
const array3 = [
{name: peanuts, referenceKey: 0, opened: 3},
{name: almond, referenceKey: 1, opened: 1},
{name: nuts, referenceKey: 2, opened: 0},
{name: cream, referenceKey: 3, opened: 2}
]
I attempted to group array2
by name using the Reduce() method as shown below :
const groupByName = (products, name) => {
return products.reduce((acc, obj) => {
var key = obj[name];
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj);
return acc
}, [])
};
const groupByName = groupByReference(array2, "name")
console.log(groupByName)
output of groupByName:
[
[peanuts:
[
{name: peanuts, expirationDate: "30d", referenceKey: 0, otherKey: 42},
{name: peanuts, expirationDate: "20d", referenceKey:0, otherKey: 43},
{name: peanuts, expirationDate: "15h", referenceKey:0, otherKey: 44},
],
cream: [
{name: cream, expirationDate: "1d", referenceKey: 3, otherKey: 46 },
{name: cream, expirationDate: "12h", referenceKey: 3, otherKey: 47}
],
almond: [
{name: almond, expirationDate: "30d", referenceKey:1, otherKey: 45},
]
]
Next, I tried to determine the length of each array but faced difficulties. Despite attempting to utilize the Map() method, it did not provide me with the expected results.
Even when explicitly mentioning an index like groupByName['peanuts']
, the console.log() returned the correct array. However, trying to access groupByName['peanuts'].length
did not work as intended.