I have an array orders
that are objects of orders made. I want to make a report out of this and create a way to remove any duplicates based on id but would like to keep the data of bookId
and count
in a new array. I also am attempting to add the counts together if multiple counts exist for the same id.
I am having issues achieving this and not sure which direction to take.
First I have
orderList
which is an array of all bookIds, count and nameSecond I tried using new Set to remove any duplicates from
orders
Third I am try add
orders
if the the userIds fromorderList
andorders
are a match.
Here is an example of my snippet:
const orders = [
{
"userId": 1,
"name": "Person 1",
"status": "active",
"bookId": 24,
"count": 1
},
{
"userId": 1,
"name": "Person 1",
"status": "active",
"bookId": 25,
"count": 2
},
{
"userId": 2,
"name": "Person 2",
"status": "active",
"bookId": 8,
"count": 2
}, {
"userId": 1,
"name": "Person 1",
"status": "active",
"bookId": 24,
"count": 3
}, {
"userId": 3,
"name": "Person 3",
"status": "active",
"bookId": 99,
"count": 1
}
]
const orderList = orders.map(item => ({count: item.count, id: item.bookId, userId: item.userId}))
const uniqueOrder = [...new Set(orders)]
let results = orderList.map(item => ({ ...item,
orders: uniqueOrder.filter(f => f.userId == item.userId)
}));
console.log(results)
Here is an example of the orders
array:
const orders = [
{
"userId": 1,
"name": "Person 1",
"status": "active",
"bookId": 24,
"count": 1
},
{
"userId": 1,
"name": "Person 1",
"status": "active",
"bookId": 25,
"count": 2
},
{
"userId": 2,
"name": "Person 2",
"status": "active",
"bookId": 8,
"count": 2
}, {
"userId": 1,
"name": "Person 1",
"status": "active",
"bookId": 24,
"count": 3
}, {
"userId": 3,
"name": "Person 3",
"status": "active",
"bookId": 99,
"count": 1
}
]
console.log(orders)
I am expecting an outcome that looks like:
const results = [
{
userId: 1,
name: 'Person 1',
status: 'active',
orders: [
{
bookId: 24,
count: 4,
},
{
bookId: 25,
count: 2,
},
],
},
{
userId: 2,
name: 'Person 2',
status: 'active',
orders: [
{
bookId: 25,
count: 2,
},
],
},
{
userId: 3,
name: 'Person 3',
status: 'active',
orders: [
{
bookId: 99,
count: 1,
},
],
},
];
console.log(results);
CodePudding user response:
You can separate the orders by user Id into a map. Then you can check to see if you have already added an order that matches that book id, then aggregate the count of the books.
Then you can return the values from the map.
const aggregateOrders = orders => {
// Separate orders in a map by user id to combine them
const resultMap = {};
for (let i = 0; i < orders.length; i ) {
const order = orders[i];
// If the user id of the order does not exist in the map, make an entry
if (!resultMap[order.userId]) {
resultMap[order.userId] = {
userId: order.userId,
name: order.name,
status: order.status,
orders: [],
};
}
// Find the order with the matching book ID, if it exists increment count, or add a new entry
const existingOrderWithMatchingBookId = resultMap[order.userId].orders.find(o => o.bookId === order.bookId);
if (existingOrderWithMatchingBookId) {
existingOrderWithMatchingBookId.count = order.count;
} else {
resultMap[order.userId].orders.push({
bookId: order.bookId,
count: order.count,
});
}
}
return Object.values(resultMap);
};
CodePudding user response:
I have prepared a small algo for you. Reduce method iterate on the array and makes sure to remove duplicates with hash map methodology and sums up count if the same book is bought by the same user more than once.
const result = orders.reduce((acc = {}, order) => {
if (acc[order.userId]) {
let existingItem = acc[order.userId];
const { orders = [] } = existingItem || {};
const indexOfSameBook = orders.findIndex(
({ bookId }) => order.bookId === bookId
);
if (indexOfSameBook > -1) {
orders[indexOfSameBook] = {
bookId: order.bookId,
count: orders[indexOfSameBook].count order.count
};
} else {
orders.push({ bookId: order.bookId, count: order.count });
}
existingItem = {
...existingItem,
orders
};
return { ...acc, [order.userId]: existingItem };
} else {
return {
...acc,
[order.userId]: {
userId: order.userId,
name: order.name,
status: order.status,
orders: [{ bookId: order.bookId, count: order.count }]
}
};
}
}, {});
Also attaching a sandbox so you can check and test: https://codesandbox.io/s/sparkling-hill-1olun5?file=/src/index.js:504-1375