Using reduce to get sum of an object - javascript

I want to have a sum of all the particulars which are in selectedIds array.
return [
{
id: 1244,
name: "Installment 1",
amount: 10000,
due_date: new Date(),
particulars: [
{
id: 2415123,
name: "Development Fee",
amount: 5000,
},
{
id: 14123,
name: "Library Fee",
amount: 3000,
},
{
id: 5123151,
name: "Sports Fee",
amount: 2000,
},
]
},
{
id: 1412,
name: "Installment 2",
amount: 6000,
due_date: new Date(),
particulars: [
{
id: 414,
name: "Development Fee",
amount: 5000,
},
{
id: 5123,
name: "Library Fee",
amount: 3000,
},
{
id: 515151,
name: "Sports Fee",
amount: 2000,
},
]
const selectedIds = [14123, 414];
In the object, I want to have a sum of all the particulars which are in selectedIds array.
I was trying to use array function to get the result. This is what I could come up with.
const selectedInstallments = this.studentInstallments
.filter((installment) =>
installment.particulars.some((particular) =>
this.selectedParticulars.includes(particular.id)
)
)
.map((installment) => installment.particulars);
console.log(selectedInstallments);
const sumParticularReducer = (acc, current) => {
return acc;
};
I couldn't figure out how to use reduce to get the result.

Please try this code.
const selectedIds = [14123, 414];
const sum = arr.reduce((prev, cur) => {
return prev + cur.particulars.reduce((old, item) => (
selectedIds.indexOf(item.id) >= 0 ? old + item.amount : old
), 0);
}, 0);
console.log(sum);

Something like:
const selectedIds = [14123, 414];
const idsArray = [{
id: 1244,
name: "Installment 1",
amount: 10000,
due_date: new Date(),
particulars: [{
id: 2415123,
name: "Development Fee",
amount: 5000,
},
{
id: 14123,
name: "Library Fee",
amount: 3000,
},
{
id: 5123151,
name: "Sports Fee",
amount: 2000,
},
]
},
{
id: 1412,
name: "Installment 2",
amount: 6000,
due_date: new Date(),
particulars: [{
id: 414,
name: "Development Fee",
amount: 5000,
},
{
id: 5123,
name: "Library Fee",
amount: 3000,
},
{
id: 515151,
name: "Sports Fee",
amount: 2000,
},
]
}
]
const sum = idsArray.reduce((sum, value) => sum + value.particulars.reduce(
(partSum, partValue) => selectedIds.includes(partValue.id) ? (partSum + partValue.amount) : partSum, 0),
0
);
console.log(sum);

const data = [{
id: 1244,
name: "Installment 1",
amount: 10000,
due_date: new Date(),
particulars: [{
id: 2415123,
name: "Development Fee",
amount: 5000,
},
{
id: 14123,
name: "Library Fee",
amount: 3000,
},
{
id: 5123151,
name: "Sports Fee",
amount: 2000,
},
]
},
{
id: 1412,
name: "Installment 2",
amount: 6000,
due_date: new Date(),
particulars: [{
id: 414,
name: "Development Fee",
amount: 5000,
},
{
id: 5123,
name: "Library Fee",
amount: 3000,
},
{
id: 515151,
name: "Sports Fee",
amount: 2000,
},
]
}
]
const selectedIds = [14123, 414];
const result = selectedIds.reduce(
(acc, id) => acc + data.reduce(
(acc, { particulars }) =>
acc + (particulars.find(p => p.id === id)?.amount || 0)
, 0)
, 0)
console.log(result)

Related

Turning array of objects into an organized object - javascript

I'm trying to manipulate this object so it matches the corresponding count to its id.
const data= [
[
{id: "333", count: 555},
{id: "2", count: 133},
{id: "444", count: 13},
{id: "433", count: 32},
{id: "3333", count: 2}
],
[
{id: "333", count: 5565},
{id: "2", count: 1633},
{id: "444", count: 136},
{id: "433", count: 362},
{id: "3333", count: 62}
],
[
{id: "333", count: 585},
{id: "2", count: 1383},
{id: "444", count: 138},
{id: "433", count: 328},
{id: "3333", count: 82}
],
]
To this:
const newData = [
{ id: "333", count: [555, 5565, 585] },
{ id: "2", count: [133, 1633, 1383] },
{ id: "444", count: [13, 136, 138] },
{ id: "433", count: [32, 362, 328] },
{ id: "3333", count: [2, 62, 82] }
]
Something I tried was this, but this just gave me an array with each count seperate.
let ob = test.reduce( ( acc, e, i) => {
let obj = {}
e.forEach((value, index) => {
obj[value.recommendationItemIdExternal] = [value.recommendationItemRating];
})
acc.push(obj);
return acc
}, [] );
You can easily achieve this result using Map and reduce
const data = [
[
{ id: "333", count: 555 },
{ id: "2", count: 133 },
{ id: "444", count: 13 },
{ id: "433", count: 32 },
{ id: "3333", count: 2 },
],
[
{ id: "333", count: 5565 },
{ id: "2", count: 1633 },
{ id: "444", count: 136 },
{ id: "433", count: 362 },
{ id: "3333", count: 62 },
],
[
{ id: "333", count: 585 },
{ id: "2", count: 1383 },
{ id: "444", count: 138 },
{ id: "433", count: 328 },
{ id: "3333", count: 82 },
],
];
const map = new Map(),
newData = [];
const dict = data.flat().reduce((acc, curr) => {
!acc.has(curr.id)
? map.set(curr.id, [curr.count])
: map.get(curr.id).push(curr.count);
return acc;
}, map);
for (let [id, count] of dict) {
newData.push({ id, count });
}
console.log(newData);
A nested for loop will do it. Just iterate through the data and store the count (or b) value in another object, using the id as the key.
let adjusted = {};
data.forEach(e => {
for (let item of e) {
if (adjusted[item.id] == undefined)
adjusted[item.id] = [];
if(item.count != undefined)
adjusted[item.id].push(item.count);
else if(item.b != undefined)
adjusted[item.id].push(item.b);
}
});
console.log(adjusted);
const data = [
[{
id: "333",
count: 555
},
{
id: "2",
count: 133
},
{
id: "444",
count: 13
},
{
id: "433",
count: 32
},
{
id: "3333",
count: 2
},
],
[{
id: "333",
count: 5565
},
{
id: "2",
count: 1633
},
{
id: "444",
count: 136
},
{
id: "433",
count: 362
},
{
id: "3333",
count: 62
},
],
[{
id: "333",
b: 585
},
{
id: "2",
b: 1383
},
{
id: "444",
b: 138
},
{
id: "433",
b: 328
},
{
id: "3333",
b: 82
},
],
]
let adjusted = {};
data.forEach(e => {
for (let item of e) {
if (adjusted[item.id] == undefined)
adjusted[item.id] = [];
if(item.count != undefined)
adjusted[item.id].push(item.count);
else if(item.b != undefined)
adjusted[item.id].push(item.b);
}
});
console.log(adjusted);
You can use a combination of .reduce() and .map() array methods as in the demo below.
const newArray = data.reduce((acc, cur) => cur.map((o, i) => ({
id: o.id,
count: [...(acc[i] && acc[i].count || []), o.count]
})), []);
Please note that this only works if each element of the original array has the ids in the same order, otherwise a little more processing is required.
DEMO
const data= [
[
{id: "333", count: 555},
{id: "2", count: 133},
{id: "444", count: 13},
{id: "433", count: 32},
{id: "3333", count: 2}
],
[
{id: "333", count: 5565},
{id: "2", count: 1633},
{id: "444", count: 136},
{id: "433", count: 362},
{id: "3333", count: 62}
],
[
{id: "333", count: 585},
{id: "2", count: 1383},
{id: "444", count: 138},
{id: "433", count: 328},
{id: "3333", count: 82}
],
];
const newArray = data.reduce((acc,cur) => cur.map((o,i) => ({id:o.id,count:[...(acc[i] && acc[i].count || []),o.count]})),[]);
console.log( newArray );

Sort Nested Javascript

const list= [
{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [{ id: 1, amount: 15, dueDate: '2021-09-01' },{ id: 2,
amount: 5, dueDate: '2021-03-01' }],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [{ id: 1, amount: 20, dueDate: '2021-11-01' },{ id: 2,
amount: 24, dueDate: '2021-09-01' },{ id: 3, amount: 1, dueDate:
'2021-10-01' }],
},
{ id: 3, amount: 10, dueDate: '2021-08-01' },
{ id: 4, amount: 30, dueDate: '2021-06-01', splits: [{ id: 1, amount: 30, dueDate: '2021-01-01' }] },
{ id: 5, amount: 15, dueDate: '2021-04-01' },
];
I want to write function that sorts a list of invoices by due date (ascending) and returns a list of object containing the invoice id with below conditions:
1- For invoices with splits, sort by earliest split's due date,or invoice 1
(id: 1) the earliest would be split 2 (id: 2).
2- For invoices without splits, the earliest dueDate is the top-level due date.
Expected sorted invoices: [{"id": 4}, {"id": 1}, {"id": 5}, {"id": 3}, {"id": 2}]
function sortFun(a,b){
if(a.splits){
a = a.splits.sort(sortFun)[0]
}
if(b.splits){
b = b.splits.sort(sortFun)[0]
}
return new Date(a.dueDate) - new Date(b.dueDate)
}
let result = list.sort(sortFun).map(x=>({id:x.id}));
console.log(result)
const list = [{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [{
id: 1,
amount: 15,
dueDate: '2021-09-01'
}, {
id: 2,
amount: 5,
dueDate: '2021-03-01'
}],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [{
id: 1,
amount: 20,
dueDate: '2021-11-01'
}, {
id: 2,
amount: 24,
dueDate: '2021-09-01'
}, {
id: 3,
amount: 1,
dueDate: '2021-10-01'
}],
},
{
id: 3,
amount: 10,
dueDate: '2021-08-01'
},
{
id: 4,
amount: 30,
dueDate: '2021-06-01',
splits: [{
id: 1,
amount: 30,
dueDate: '2021-01-01'
}]
},
{
id: 5,
amount: 15,
dueDate: '2021-04-01'
},
];
function sortFun(a,b){
if(a.splits){
a = a.splits.sort(sortFun)[0]
}
if(b.splits){
b = b.splits.sort(sortFun)[0]
}
return new Date(a.dueDate) - new Date(b.dueDate)
}
let result = list.sort(sortFun).map(x=>({id:x.id}));
console.log(result)
You could do something like:
list.sort((prev, next) => {
let prevDueDate = prev.splits ? prev.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : prev.dueDate;
let nextDueDate = next.splits ? next.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : next.dueDate;
return prevDueDate.localeCompare(nextDueDate);
}).map(el => ({ id: el.id }));
See these references for more help:
MDN - Array.prototype.sort()
MDN - String.prototype.localeCompare()
const list= [
{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [{ id: 1, amount: 15, dueDate: '2021-09-01' },{ id: 2,
amount: 5, dueDate: '2021-03-01' }],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [{ id: 1, amount: 20, dueDate: '2021-11-01' },{ id: 2,
amount: 24, dueDate: '2021-09-01' },{ id: 3, amount: 1, dueDate:
'2021-10-01' }],
},
{ id: 3, amount: 10, dueDate: '2021-08-01' },
{ id: 4, amount: 30, dueDate: '2021-06-01', splits: [{ id: 1, amount: 30, dueDate: '2021-01-01' }] },
{ id: 5, amount: 15, dueDate: '2021-04-01' },
];
let res = list.sort((prev, next) => {
let prevDueDate = prev.splits ? prev.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : prev.dueDate;
let nextDueDate = next.splits ? next.splits.map(el => el.dueDate).sort((a, b) => a.localeCompare(b))[0] : next.dueDate;
return prevDueDate.localeCompare(nextDueDate);
}).map(el => ({ id: el.id }));
console.log(res);
Hope this is the solution that you are looking for.
const list = [
{
id: 1,
amount: 20,
dueDate: '2021-05-01',
splits: [
{ id: 1, amount: 15, dueDate: '2021-09-01' },
{ id: 2, amount: 5, dueDate: '2021-03-01' }
],
},
{
id: 2,
amount: 45,
dueDate: '2021-07-01',
splits: [
{ id: 1, amount: 20, dueDate: '2021-11-01' },
{ id: 2, amount: 24, dueDate: '2021-09-01' },
{ id: 3, amount: 1, dueDate: '2021-10-01' }
],
},
{
id: 3,
amount: 10,
dueDate: '2021-08-01'
},
{
id: 4,
amount: 30,
dueDate: '2021-06-01',
splits: [{ id: 1, amount: 30, dueDate: '2021-01-01' }]
},
{
id: 5,
amount: 15,
dueDate: '2021-04-01'
},
];
const getDateForObj = (obj) => {
if (obj.splits) {
const dateList = obj.splits.map((split) => split.dueDate);
const smallestDate = dateList.sort((a, b) => new Date(a) - new Date(b))[0];
return smallestDate;
} else {
return obj.dueDate
}
}
const newList = list.sort((a, b) =>{
const aDate = getDateForObj(a);
const bDate = getDateForObj(b);
return new Date(aDate) - new Date(bDate);
});
console.log(newList);

How to create a nested array of object from an array of objects

How Can I loop through this array of objects and change it so that the individual menu items are nested in the object menu_name?
const menus = [
{ menu_name: 'Entre', id:0 },
{
name: 'Soup',
price: 14.99,
id:1
},
{
name: 'Chips & Salsa',
price: 7.99,
id:2
},
{
name: 'Chicken Nuggets',
price: 12.99,
id:3
},
{ menu_name: 'Sides', id:4 },
{
name: 'Fries',
price: 4.99,
id:5
},
{
name: 'Drinks',
price: 2.99,
id:6
},
{
name: 'Onion Rings',
price: 5.99,
id:7
},
];
the end result should look like this for each menu_name object, where an array of menus is nested in the menu_name object
{
menu_name: 'Sides',
menu: [
{
name: 'Fries',
price: 4.99,
},
{
name: 'Drinks',
price: 2.99,
},
{
name: 'Onion Rings',
price: 5.99,
},
],
},
You can easily achieve this using reduce and object destructuring
const menus = [
{ menu_name: "Entre", id: 0 },
{
name: "Soup",
price: 14.99,
id: 1,
},
{
name: "Chips & Salsa",
price: 7.99,
id: 2,
},
{
name: "Chicken Nuggets",
price: 12.99,
id: 3,
},
{ menu_name: "Sides", id: 4 },
{
name: "Fries",
price: 4.99,
id: 5,
},
{
name: "Drinks",
price: 2.99,
id: 6,
},
{
name: "Onion Rings",
price: 5.99,
id: 7,
},
];
const result = menus.reduce((acc, curr) => {
const { menu_name } = curr;
if (menu_name) {
acc.push({ menu_name, menu: [] });
} else {
const { name, price } = curr;
acc[acc.length - 1].menu.push({ name, price });
}
return acc;
}, []);
console.log(result);
var newMenu = [];
menus.forEach(menu=>{
if(menu.menu_name){
newMenu.push({...menu, menu: []})
}else{
newMenu[newMenu.length-1].menu.push(menu)
}
});

How do I get the total sum of nested arrays in Reactjs?

I want to get the total price of nested arrays in a specific category e.g: Hot Drinks.
Here is a sample of what I have now, so I want to filter out and get the total price of Hot Drinks Category only.
[
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
]
You can apply a filter method on the array and then just add the values on the filtered array. Something like below:
let prod = [
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
];
function getPriceByCategory(category, products) {
let price = 0;
products.forEach(orders => {
orders.orderItems.filter(order => order.category == category).forEach(item => {
price += item.price;
});
});
return price;
}
const totalPrice = getPriceByCategory('Hot Drinks', prod);
alert(totalPrice);
Sample JS Fiddle: https://jsfiddle.net/sagarag05/qwzju53f/9/
const filterBy = 'Hot Drinks';
const items = [
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
]
const sumOf = (items, filterBy) => {
let totalPrice = 0;
items.forEach(item => {
item.orderItems.forEach(orderItem => {
if (orderItem.category === filterBy) {
totalPrice += orderItem.price;
}
})
})
return totalPrice;
}
console.log(sumOf(items, filterBy))
let sum = 0;
allOrders.forEach(order => {
order.orderItems.forEach(item => {
if(item.category=='Hot Drinks') {
sum+ = item.price * item.qty
}});
});
sum has the total price for Hot Drinks
Assuming you named that information as data:
Generate a big array of all the "orderItems"
For each of those elements sum the price if the category is "Hot Drinks"
const totalPrice = data
.reduce((acc, { orderItems }) => [...acc, ...orderItems], [])
.reduce((acc, { category, price }) => category === "Hot Drinks" ? acc + price : acc, 0);
console.log(totalPrice); // 10
Use flatMap and reduce or alternatively using forEach and destructuring
const total = (arr, text) =>
arr
.flatMap(({ orderItems }) => orderItems)
.reduce((acc, { category, price }) =>
(acc + (category === text ? price : 0)), 0);
// alternatively
const total2 = (arr, text, acc = 0) => {
arr.forEach(({ orderItems }) =>
orderItems.forEach(
({ category, price }) => (category === text && (acc += price))
)
);
return acc;
};
const data = [
{
totalPrice: 30,
_id: "6014fa4324e125599eaa72b5",
orderItems: [
{
_id: "6014fa4324e125599eaa747ss",
category: "Breakfast",
name: "food name 1",
price: 3,
qty: 1,
},
{
_id: "6014fa4324e125599eaa747s5",
category: "Hot Drinks",
name: "drink name 1",
price: 3,
qty: 5,
},
{
_id: "6014fa4324e125599eaa74767",
category: "Hot Drinks",
name: "drink name 2",
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: "6014fa4324e125599eaa7276e",
orderItems: [
{
_id: "6014fa4324e125599eaa747ss",
category: "Hot Drinks",
name: "drink name 1",
price: 3,
qty: 6,
},
],
},
];
console.log(total(data, 'Hot Drinks'))
console.log(total2(data, 'Hot Drinks'))

ES6: Populate object value with a value from another object when ID is present

I would like to populate the value 'discount' for a product with the discount ID value from the array discounts, if the respective product ID exists as a value in the Discounts object.
const products = [{
id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d",
name: "SANTO - Schnürstiefelette",
price: 199.95,
discount: 0,
},
{
id: "1b9b6c7e-c856-464c-ba64-98c9dd6733b5",
name: "AIR FORCE 1 07 LV8 - Sneaker low",
price: 109.95,
discount: 0,
},
{
id: "f831aaf4-347a-458f-bb0c-21cf02aeac2e",
name: "DUFF 9.0 - Sporttasche",
price: 34.95,
discount: 0,
},
{
id: "471ad894-150b-4a2b-881c-a9a4dbc4b401",
name: "Strickpullover",
price: 20.99,
discount: 0,
},
];
const discounts = [{
id: "5791ae04-a704-4f44-808b-de5ddb8812b5",
name: "Christmas discount",
productIds: ["1b9b6c7e-c856-464c-ba64-98c9dd6733b5", "f831aaf4-347a-458f-bb0c-21cf02aeac2e"],
active: true
},
{
id: "5791ae04-a704-4f44-808b-de5ddb8812e6",
name: "Christmas discount 2",
productIds: ["05cdb75d-7984-4dbf-b0f4-d6532163b66d"],
active: true
}
];
At the end i need it like:
const products = [{
id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d",
name: "SANTO - Schnürstiefelette",
price: 199.95,
discount: '5791ae04-a704-4f44-808b-de5ddb8812e6',
},
...
...
You could use map() to transform products array. And find() and includes() to check if discount exists for a product.
const products = [{ id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d", name: "SANTO - Schnürstiefelette", price: 199.95, discount: 0, }, { id: "1b9b6c7e-c856-464c-ba64-98c9dd6733b5", name: "AIR FORCE 1 07 LV8 - Sneaker low", price: 109.95, discount: 0, }, { id: "f831aaf4-347a-458f-bb0c-21cf02aeac2e", name: "DUFF 9.0 - Sporttasche", price: 34.95, discount: 0, }, { id: "471ad894-150b-4a2b-881c-a9a4dbc4b401", name: "Strickpullover", price: 20.99, discount: 0, }, ];
const discounts = [{ id: "5791ae04-a704-4f44-808b-de5ddb8812b5", name: "Christmas discount", productIds: ["1b9b6c7e-c856-464c-ba64-98c9dd6733b5", "f831aaf4-347a-458f-bb0c-21cf02aeac2e"], active: true }, { id: "5791ae04-a704-4f44-808b-de5ddb8812e6", name: "Christmas discount 2", productIds: ["05cdb75d-7984-4dbf-b0f4-d6532163b66d"], active: true } ];
let result = products.map(product => {
let discount = discounts.find(item => item.productIds.includes(product.id));
return {
...product,
"discount": discount ? discount.id : product.discount
};
});
console.log(result);
You could store the discounts in a Map and map the object with a new discount object, if necessary.
var products = [{ id: "05cdb75d-7984-4dbf-b0f4-d6532163b66d", name: "SANTO - Schnürstiefelette", price: 199.95, discount: 0 }, { id: "1b9b6c7e-c856-464c-ba64-98c9dd6733b5", name: "AIR FORCE 1 07 LV8 - Sneaker low", price: 109.95, discount: 0 }, { id: "f831aaf4-347a-458f-bb0c-21cf02aeac2e", name: "DUFF 9.0 - Sporttasche", price: 34.95, discount: 0 }, { id: "471ad894-150b-4a2b-881c-a9a4dbc4b401", name: "Strickpullover", price: 20.99, discount: 0 }],
discounts = [{ id: "5791ae04-a704-4f44-808b-de5ddb8812b5", name: "Christmas discount", productIds: ["1b9b6c7e-c856-464c-ba64-98c9dd6733b5", "f831aaf4-347a-458f-bb0c-21cf02aeac2e"], active: true }, { id: "5791ae04-a704-4f44-808b-de5ddb8812e6", name: "Christmas discount 2", productIds: ["05cdb75d-7984-4dbf-b0f4-d6532163b66d"], active: true }],
ids = discounts.reduce((m, { id, productIds }) => productIds.reduce((n, pid) => n.set(pid, id), m), new Map);
products = products.map(p => Object.assign({}, p, ids.has(p.id) && { discount: ids.get(p.id) }));
console.log(products);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nested loop through both products and discounts array, if the product id is included inside the productIds array of any of the objects in the discounts array, assign the discount id to the product discount.
for (let product of products) {
for (let discount of discounts) {
if (discount.productIds.includes(product.id)){
product.discount = discount.id;
break;
}
}
}

Categories