Javascript Object Literals for property with method - javascript

const products = [
{
id: 5,
productName: "Logitech Mouse",
unitprice: 35
},
{
id: 6,
productName: "Logitech Keyboard",
unitprice: 40
}
];
const carts = [
{
id: 101,
userId: 3,
productId: 5,
quantity: 2,
total: function () {
return this.unitprice * this.quantity
}
}
];
let joined = carts.map(item => {
console.log(item.total);
let { id, ...rest } = products.find(p => p.id === item.productId);
debugger
return {
...rest, 'quantity': item.quantity,
'total': item.total
};
});
console.log(joined);
How do I get the total property for the new object at the end? I tried with the above but the total value 10 is not there. I tried another version at below but still no success.
get total() {
return this.unitprice * this.quantity
}

A getter would work, the only issue is, it won't have access to the unit price. You will have to pass through the unit price.
const products = [{
id: 5,
productName: "Logitech Mouse",
unitprice: 35
},
{
id: 6,
productName: "Logitech Keyboard",
unitprice: 40
}
];
const carts = [{
id: 101,
userId: 3,
productId: 5,
quantity: 2,
total: function(unitprice) {
return unitprice * this.quantity
}
}];
let joined = carts.map(item => {
let {
id,
unitprice,
...rest
} = products.find(p => p.id === item.productId);
debugger
return {
...rest,
'quantity': item.quantity,
'total': item.total(unitprice)
};
});
console.log(joined);

u can try:
const products = [
{
id: 5,
productName: "Logitech Mouse",
unitprice: 35
},
{
id: 6,
productName: "Logitech Keyboard",
unitprice: 40
}
];
const carts = [
{
id: 101,
userId: 3,
productId: 5,
quantity: 2,
total: function () {
return products.find(product => product.id === this.productId).unitprice * this.quantity;
}
}
];
let joined = carts.map(item => {
console.log(item.total());
let { id, ...rest } = products.find(p => p.id === item.productId);
return {
...rest, "quantity": item.quantity,
"total": item.total
};
});
console.log(joined);

let joined = carts.filter((ca)=>{
return products.some((c)=>{
//place your exact calculations here(c.id === ca.productId)
// ca.total = -- your result
return c;
})
});
Try this way.

Related

How can I see if Object Array has elements in Another Object Array?

Is there a way to tell if an object array has any common elements to another object array, and what that object intersect is? (like a Contains function). In the example below,ProductId3 in Object Array 1, is also contained in Object Array 2.
I'm thinking of using a double for loop . However is there a more efficient/optimal way, or shorthand ecma or lodash function?
We are checking all object members, not just ProductId.
array1.forEach(arr1 => {
array2.forEach(arr2 => {
if (arr1.productId === arr2.productId &&
arr1.productName === arr2.productName ...
Object Array 1:
[
{
ProductId: 50,
ProductName: 'Test1',
Location: 77,
Supplier: 11,
Quantity: 33
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}
]
Object Array 2:
[
{
ProductId: 1,
ProductName: 'ABC',
Location: 3,
Supplier: 4,
Quantity: 52
},
{
ProductId: 2,
ProductName: 'DEF',
Location: 1,
Supplier: 2,
Quantity: 87
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
},
{
ProductId: 4,
ProductName: 'XYZ',
Location: 5,
Supplier: 6,
Quantity: 17
}
]
Resources:
How to determine if Javascript array contains an object with an attribute that equals a given value?
Javascript: Using `.includes` to find if an array of objects contains a specific object
Is there a way to tell if an object array has any common elements to another object array ? - Yes you can achieve this with the help of Array.some() method. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false.
const array1 = [{
ProductId: 50,
ProductName: 'Test1',
Location: 77,
Supplier: 11,
Quantity: 33
}, {
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}];
const array2 = [{
ProductId: 1,
ProductName: 'ABC',
Location: 3,
Supplier: 4,
Quantity: 52
}, {
ProductId: 2,
ProductName: 'DEF',
Location: 1,
Supplier: 2,
Quantity: 87
}, {
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}, {
ProductId: 4,
ProductName: 'XYZ',
Location: 5,
Supplier: 6,
Quantity: 17
}];
const isCommonProducts = array2.some(({ ProductId }) => array1.map(obj => obj.ProductId).includes(ProductId));
console.log(isCommonProducts);
Update : As per the author comment, we have to check all the properties of an object. Hence, we can achieve that by comparing the JSON string by converting the object into a string.
Live Demo :
const array1 = [{
ProductId: 50,
ProductName: 'Test1',
Location: 77,
Supplier: 11,
Quantity: 33
}, {
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}];
const array2 = [{
ProductId: 1,
ProductName: 'ABC',
Location: 3,
Supplier: 4,
Quantity: 52
}, {
ProductId: 2,
ProductName: 'DEF',
Location: 1,
Supplier: 2,
Quantity: 87
}, {
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}, {
ProductId: 4,
ProductName: 'XYZ',
Location: 5,
Supplier: 6,
Quantity: 17
}];
const getFilteredProducts = array2.filter(productObj => JSON.stringify(array1).indexOf(JSON.stringify(productObj)) !== -1);
console.log(getFilteredProducts);
If we can assume that each array's elements (we will call them sub-dictionaries) contain exactly the same keys in the same order, then this is my idea:
Convert each array into a new array whose elements are the JSON representations of the original sub-dictionaries values. This is an o(N) operation performed twice.
Of the new, converted arrays find the shortest one. Convert the other into a set. This is also o(N).
For each element of the shorter converted array, check to see if the set contains this value. This is also o(N).
let arr1 = [
{
ProductId: 50,
ProductName: 'Test1',
Location: 77,
Supplier: 11,
Quantity: 33
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
}
];
let arr2 = [
{
ProductId: 1,
ProductName: 'ABC',
Location: 3,
Supplier: 4,
Quantity: 52
},
{
ProductId: 2,
ProductName: 'DEF',
Location: 1,
Supplier: 2,
Quantity: 87
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
},
{
ProductId: 4,
ProductName: 'XYZ',
Location: 5,
Supplier: 6,
Quantity: 17
}
];
// Convert each sub-array's values to JSON string:
let arr1New = arr1.map(function(arr) {return JSON.stringify(Object.values(arr));});
let arr2New = arr2.map(function(arr) {return JSON.stringify(Object.values(arr));});
// Find shortest array of JSON strings:
const l1 = arr1New.length;
const l2 = arr2New.length;
// enumerate shortest list
let list, set, l, arr;
if (l1 <= l2) {
list = arr1New;
set = new Set(arr2New);
l = l1;
arr = arr1;
}
else {
list = arr2New;
set = new Set(arr1New);
l = l2;
arr = arr2;
}
for(let i = 0; i < l; i++) {
if (set.has(list[i])) {
console.log(arr[i]);
}
}
Update
If the sub-dictionary keys are not necessarily in order, then we have to create new sub-dictionaries from these where the keys are in order:
// Create function to create new dictionaries sorted by keys
function sort_dict(d) {
items = Object.keys(d).map(function(key) {
return [key, d[key]];
});
items.sort(function(first, second) {
return first[0] < second[0] ? -1 : (first[0] > second[0] ? 1 : 0);
});
sorted_dict = {};
items.forEach(function(x) {
sorted_dict[x[0]] = x[1];
});
return(sorted_dict);
}
// And then we have these modified lines:
// Convert each sub-array's values to JSON string:
let arr1New = arr1.map(function(arr) {return JSON.stringify(Object.values(sort_dict(arr)));});
let arr2New = arr2.map(function(arr) {return JSON.stringify(Object.values(sort_dict(arr)));});
Modified Code
let arr1 = [
{
ProductId: 50,
ProductName: 'Test1',
Location: 77,
Supplier: 11,
Quantity: 33
},
{
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25,
ProductId: 3 // Not in the same order as the others
}
];
let arr2 = [
{
ProductId: 1,
ProductName: 'ABC',
Location: 3,
Supplier: 4,
Quantity: 52
},
{
ProductId: 2,
ProductName: 'DEF',
Location: 1,
Supplier: 2,
Quantity: 87
},
{
ProductId: 3,
ProductName: 'GHI',
Location: 1,
Supplier: 4,
Quantity: 25
},
{
ProductId: 4,
ProductName: 'XYZ',
Location: 5,
Supplier: 6,
Quantity: 17
}
];
function sort_dict(d) {
items = Object.keys(d).map(function(key) {
return [key, d[key]];
});
items.sort(function(first, second) {
return first[0] < second[0] ? -1 : (first[0] > second[0] ? 1 : 0);
});
sorted_dict = {};
items.forEach(function(x) {
sorted_dict[x[0]] = x[1];
});
return(sorted_dict);
}
// Convert each sub-array's values to JSON string:
let arr1New = arr1.map(function(arr) {return JSON.stringify(Object.values(sort_dict(arr)));});
let arr2New = arr2.map(function(arr) {return JSON.stringify(Object.values(sort_dict(arr)));});
// Find shortest array of JSON strings:
const l1 = arr1New.length;
const l2 = arr2New.length;
// enumerate shortest list
let list, set, l, arr;
if (l1 <= l2) {
list = arr1New;
set = new Set(arr2New);
l = l1;
arr = arr1;
}
else {
list = arr2New;
set = new Set(arr1New);
l = l2;
arr = arr2;
}
for(let i = 0; i < l; i++) {
if (set.has(list[i])) {
console.log(arr[i]);
}
}
For a simple yet reasonably fast solution, you can (1) use a Set of productIds from the first array, then (2) filter the second array based on the ids from the first one, this you only have to go over each array once O(n).
let arr1 = [
{
ProductId: 50,
ProductName: "Test1",
Location: 77,
Supplier: 11,
Quantity: 33,
},
{
ProductId: 3,
ProductName: "GHI",
Location: 1,
Supplier: 4,
Quantity: 25,
},
];
let arr2 = [
{
ProductId: 1,
ProductName: "ABC",
Location: 3,
Supplier: 4,
Quantity: 52,
},
{
ProductId: 2,
ProductName: "DEF",
Location: 1,
Supplier: 2,
Quantity: 87,
},
{
ProductId: 3,
ProductName: "GHI",
Location: 1,
Supplier: 4,
Quantity: 25,
},
{
ProductId: 4,
ProductName: "XYZ",
Location: 5,
Supplier: 6,
Quantity: 17,
},
];
const getCommonItems = (arr1, arr2) => {
let firstIdSet = new Set(arr1.map((product) => product.ProductId)); //1
return arr2.filter((product) => firstIdSet.has(product.ProductId)); //2
};
console.log(getCommonItems(arr1, arr2));
If you want a deep equality comparison(for nested objects or for all (key, value) pairs), I would suggest a slightly better approach which is using the base64 encoding/decoding to improve on comparison performance.
So my approach is to:
merge the arrays and convert the object to base64 strings.
Group the recurrences together
Filter on duplicates
revert the base64 strings into their original object.
const convertObjToBase64 = o => btoa(JSON.stringify(o));
const convertBase64ToObj = str => JSON.parse(atob(str));
const arrayToObjCount = arr => arr.reduce((res, v) => {
res[v] = (res[v] ?? 0) + 1;
return res;
}, {});
const findDuplicateObjectsInMultipleArrays = (...arrays) => {
const base64Array = Array.from(arrays.flat(), convertObjToBase64);
const objCount = arrayToObjCount(base64Array);
const duplicates = Object.entries(objCount).reduce((prev, [k, v]) => {
if (v > 1) {
prev.push(convertBase64ToObj(k));
}
return prev;
}, []);
return duplicates;
}
let arr1 = [{
ProductId: 50,
ProductName: 'Test1',
Location: {
LocationId: 77,
LocationName: 'Location 77'
},
Supplier: 11,
Quantity: 33
},
{
ProductId: 3,
ProductName: 'GHI',
Location: {
LocationId: 1,
LocationName: 'Location 1'
},
Supplier: 4,
Quantity: 25
}
];
let arr2 = [{
ProductId: 1,
ProductName: 'ABC',
Location: {
LocationId: 3,
LocationName: 'Location 3'
},
Supplier: 4,
Quantity: 52
},
{
ProductId: 2,
ProductName: 'DEF',
Location: {
LocationId: 1,
LocationName: 'Location 1'
},
Supplier: 2,
Quantity: 87
},
{
ProductId: 3,
ProductName: 'GHI',
Location: {
LocationId: 1,
LocationName: 'Location 1'
},
Supplier: 4,
Quantity: 25
},
{
ProductId: 4,
ProductName: 'XYZ',
Location: {
LocationId: 5,
LocationName: 'Location 5'
},
Supplier: 6,
Quantity: 17
}
];
let arr3 =[
{
ProductId: 2,
ProductName: 'DEF',
Location: {
LocationId: 1,
LocationName: 'Location 1'
},
Supplier: 2,
Quantity: 87
},
{
ProductId: 3,
ProductName: 'GHI',
Location: {
LocationId: 2,
LocationName: 'Location 2'
},
Supplier: 4,
Quantity: 25
},
{
ProductId: 4,
ProductName: 'XYZ',
Location: {
LocationId: 6,
LocationName: 'Location 5'
},
Supplier: 6,
Quantity: 17
}
];
console.log(findDuplicateObjectsInMultipleArrays(arr1, arr2, arr3));
I will post two solutions:
First Solution is readable one
Code is not 100% performance optimized, but it is readable and elegant.
Playground link with working code
First, we need a method that compares two objects of any type. The method compares the first-level properties, so if we have nested object properties, it will compare them by reference.
const areTheSame = (a: any, b: any) => {
const objAProps = Object.keys(a).filter(key => typeof a[key] !== "function")
const objBProps = Object.keys(b).filter(key => typeof b[key] !== "function")
if (objAProps.length !== objBProps.length) {
return false;
}
return objAProps.every((propName) => a[propName] === b[propName]);
}
And then we can implement readable intersect method which will work for any array types:
const getIntersection = (array1: Array<any>, array2: Array<any>) => {
return array1.filter(a1Item => array2.some(a2Item => areTheSame(a1Item, a2Item)));
}
The Second solution is performance-oriented, its drawback is that it is not so readable
First, we calculate the has for all objects, then within a single forEach loop we can identify the intersection based on that Hash. I have used md5, but any hash algorithm or library can be used.
Hers is stack blitz link playground. It can be run, ignore the import error.
const getArrayIntersection = (
firstArray: Array<any>,
secondArray: Array<any>
) => {
const array1Hashed = firstArray.map((i) => md5(JSON.stringify(i)));
const array2Set = new Set(secondArray.map((i) => md5(JSON.stringify(i))));
const result: Array<any> = [];
array1Hashed.forEach((itemHash, index) => {
if (array2Set.has(itemHash)) {
result.push(firstArray[index]);
}
});
return result;
};
Just to piggyback #Rohìt Jíndal, you can check if an array has a specific object like so:
const resultObj = arr1.filter(obj => obj.id=== "whatever" && obj.productname == "whatever") // ETC ETC

How to get the total amount of the orders? (ReactJS)

order history
I would like to get the total amounts per order, however, I cannot get the value of the quantity in an array
Quantity in an array
I would like to know how to get the value of the quantity in the array so that I can multiply it by to order amount? Or is there another way to get the total amount of the orders?
It's not very clear what you want to do with the quantity, nor how you will get the price of the product, but I try to give some help anyway.
Let's say you have an orders array, if you just need to extract all the quantities you can just do like this:
orders.forEach(order => {
const products = order.products;
products.forEach(product => {
const quantity = product.quantity;
console.log(quantity);
});
});
If you had a function that can give you the price of the single item, for example something like getProductValue() you can compute the total like this:
orders.forEach(order => {
const products = order.products;
products.forEach(product => {
const quantity = product.quantity;
const value = getProductValue(product.id);
const total = quantity * value;
console.log(total);
});
});
You can also create an array with all the amounts like this:
const allAmounts = orders.reduce((valuesList, order) => {
const products = order.products;
const values = products.map(product => {
const quantity = product.quantity;
const value = getProductValue(product.id);
const total = quantity * value;
return total;
});
valuesList = valuesList.concat(values);
return valuesList;
}, []);
Or you can even sum all the values like this:
const totalSum = orders.reduce((totalOrderValue, order) => {
const products = order.products;
const productSum = products.reduce((totalProductValue, product) => {
const quantity = product.quantity;
const value = getProductValue(product.id);
const total = quantity * value;
return totalProductValue += total;
}, 0);
totalOrderValue = totalOrderValue + productSum;
return totalOrderValue;
}, 0);
Here is a complete snippet with a fake orders array and a fake getProductValue function and the totalSum computation:
const orders = [
{
_id: 'xxx',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 4,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 2,
}
]
},
{
_id: 'dddd',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 2,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 23,
}
]
},
{
_id: 'eee',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 7,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 2,
}
]
},
{
_id: 'zzzz',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 2,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 1,
}
]
},
{
_id: 'hhh',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 1,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 1,
}
]
},
{
_id: 'wedsd',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 78,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 8,
}
]
},
{
_id: 'wedsd',
products: [
{
title: 'ptitle',
id: 'dfsdsge',
quantity: 6,
},
{
title: 'ptitle',
id: 'sdfrer',
quantity: 1,
}
]
}
];
const getProductValue = id => {
return 5;
}
const totalSum = orders.reduce((totalOrderValue, order) => {
const products = order.products;
const productSum = products.reduce((totalProductValue, product) => {
const quantity = product.quantity;
const value = getProductValue(product.id);
const total = quantity * value;
return totalProductValue += total;
}, 0);
totalOrderValue = totalOrderValue + productSum;
return totalOrderValue;
}, 0);
console.log(totalSum);
Something along the lines:
let sumOfQuantity = 0;
ORDERS[3].products.forEach(x => {
sumOfQuantity += x.quantity;
})
console.log("Total: " + (ORDERS[3].amount * sumOfQuantity))
If you need to do this for every order just do ORDERS.forEach in the same mannor

Javascript how to merge objects with same product id and summarize quantity

I have a cart with a bunch of products, based on this array:
[
{
product_id: 123,
price: 100,
quantity: 1,
item: { ... some more data }
},
{
product_id: 200,
price: 199,
quantity: 1,
item: { ... some more data }
},
{
product_id: 123,
price: 100,
quantity: 2,
item: { ... some more data }
},
etc...
]
So, when a product has been added multiple times, it should "merge" them into one object and the output to be like:
[
{
product_id: 123,
price: 100,
**quantity: 2,** // THIS IS VERY IMPORTANT
item: { ... some more data }
},
{
product_id: 200,
price: 199,
quantity: 1,
item: { ... some more data }
},
]
So, I've tried the following:
const output = Object.values(
items.reduce((accu, { product_id, ...item }) => {
if (!accu[product_id]) accu[product_id] = {}
accu[product_id] = { product_id, ...accu[product_id], ...item }
return accu
}, {}),
)
this actually gives me what I want, EXCEPT that the quantity is summarized.
How can I achieve that?
You have to add the accumulation logic to the quant separately
like the following example
const cart = [
{
product_id: 123,
price: 100,
quantity: 1,
},
{
product_id: 200,
price: 199,
quantity: 1,
},
{
product_id: 123,
price: 100,
quantity: 2,
},
]
const output = Object.values(
cart.reduce((accu, { product_id, ...item }) => {
if (!accu[product_id]) accu[product_id] =
{
quantity:0
}
accu[product_id] = {
product_id,
...accu[product_id],
...item,
quantity: accu[product_id].quantity + item.quantity // custom accu for quant
}
return accu;
}, {}),
)
console.log(output)

How to filter these arrays in JavaScript?

I have the following arrays:
const players = [{
id: 1,
ip: '198.199.162',
nickname: 'BIG BOSS'
}, {
id: 2,
ip: '198.199.162',
nickname: 'CHICKEN LITTLE'
}, {
id: 3,
ip: '198.199.162',
nickname: 'MR T'
}, {
id: 4,
ip: '198.199.162',
nickname: 'DONUT KING'
}];
const connectedRooms = [{
playerId: 4,
roomId: 1,
playedTime: 300
}, {
playerId: 2,
roomId: 1,
playedTime: 30
}, {
playerId: 1,
roomId: 2,
playedTime: 10
}, {
playerId: 3,
roomId: 3,
playedTime: 45
},
{
playerId: 1,
roomId: 3,
playedTime: 15
}
const rooms = [{
id: 1,
name: 'READY SET GO'
}, {
id: 2,
name: 'CHICKEN WINNER'
}, {
id: 3,
name: 'BURGER TIME'
}];
I need to filter those arrays in a way that I could tell what room has the player played in. My desired output would be the following:
{
key: BIG BOSS,
value: [CHICKEN WINNER, BURGER TIME]
}
So far my code is only listing the IDs of the rooms. I have tried ES6 filter but I only get the room Id as well.
let result = [];
for (let i = 0; i < players.length; i++) {
for (let j = 0; j < connectedRooms.length; j++) {
if (connectedRooms[j].playerId === players[i].id) {
result.push(connectedRooms[j].roomId);
}
}
}
How else could I filter these arrays to obtain the desired output?
result = [];
players.forEach(player=>{
value=[];
rooms.forEach(room=>{
if(connectedRooms.filter(connectedRoom=>connectedRoom.playerId==player.id&&connectedRoom.roomId==room.id).length>0) value.push(room.name);
})
if(value.length>0) result.push({key:player.nickname,value:value});
})
This may help you :
// for each players
players.map((player) => {
return {
key: player.nickname,
value: connectedRooms
// filter connectedRooms where the player is
.filter((connectedRoom) => {
return player.id === connectedRoom.playerId;
})
// for each filtered connectedRooms, you search room's datas
.map((connectedRoom) => {
return rooms.filter((room) => {
return room.id === connectedRoom.roomId;
}).pop().name; // i used `pop` assuming your datas can't have players connected to non-existent room
})
};
});
You need to get all room names from the connectedRooms according to the playerId then assign the room names into value property. In the end, getRooms returns an object holding all target data structures by playerId.
const getRoomNames = (playerId) => connectedRooms.reduce((acc, cr) => {
if(cr.playerId === playerId) {
const roomName = rooms.find(room => cr.roomId === room.id)?.name;
acc.push(roomName);
}
return acc;
}, []);
const getRooms = () => players.reduce((acc, player) => {
acc[player.id] = {
key: player.nickname,
value: getRoomNames(player.id)
}
return acc;
}, {});
Please use this code.
let result = {};
const playerId = 1;
const key = players.filter(val => val.id == playerId).map(val => val.nickname);
const value = connectedRooms.filter(val => val.playerId == playerId).map(val => rooms.filter(value => value.id == val.roomId)[0].name);
result = {key, value};
console.log(result);
Here is a solution that loops through each array once, using reduce.
Finds the user id.
Turns rooms into an object with roomObj[id] = name so I can do a look up instead of looping over rooms again and again.
Builds a new array of playerRooms, filtered by playerId, by adding the room name from roomObj.
function getRoomsBasedOn(nickname) {
// 1
let user = (player) => { return player.nickname == nickname };
let id = players.find(user).id; // crashes if nickname not found
// 2
let roomObj = rooms.reduce((obj, room) => (obj[room.id] = room.name, obj) ,{});
// 3
let playerRooms = connectedRooms.reduce((arr, room) => {
return (room.playerId == id) ? arr.concat(roomObj[room.roomId]) : arr;
}, []);
return {
'key': nickname,
'value': playerRooms
};
}
const players = [{
id: 1,
ip: '198.199.162',
nickname: 'BIG BOSS'
}, {
id: 2,
ip: '198.199.162',
nickname: 'CHICKEN LITTLE'
}, {
id: 3,
ip: '198.199.162',
nickname: 'MR T'
}, {
id: 4,
ip: '198.199.162',
nickname: 'DONUT KING'
}];
const connectedRooms = [{
playerId: 4,
roomId: 1,
playedTime: 300
}, {
playerId: 2,
roomId: 1,
playedTime: 30
}, {
playerId: 1,
roomId: 2,
playedTime: 10
}, {
playerId: 3,
roomId: 3,
playedTime: 45
},
{
playerId: 1,
roomId: 3,
playedTime: 15
}];
const rooms = [{
id: 1,
name: 'READY SET GO'
}, {
id: 2,
name: 'CHICKEN WINNER'
}, {
id: 3,
name: 'BURGER TIME'
}];
console.log( getRoomsBasedOn('BIG BOSS') );

Getting sum by comparing two arrays

I have 2 arrays, one that contains a list of products, and the other is an orders arrays that contains the orderinfo of multiple purchases.
For example, the products array would look like this:
const products = [
{price: 10, id: 123, ...}
,
...
]
and the orders array would look like:
const orders = [
{
shippinginfo: {...},
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [
{
id: 123,
qty: 5
}
]
}
}
]
So my question is, how exactly can i go about summing the price of all the orders in this orders array?
Looping through works ! To create it more usable added some random products ... It will give you sum of the all products in array of orders
const orders = [{
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [{
id: 123,
qty: 5
},
{
id: 13,
qty: 2
}]
}
}]
const products = [{
price: 10,
id: 123
},
{
price: 100,
id: 13
},
]
let sum = 0;
orders.forEach(order => {
order.orderinfo.products.forEach(item => {
products.forEach(product => {
if (item.id === product.id) {
sum += product.price * item.qty
}
})
})
});
console.log(sum)
We can do something like this:
const products = [{
price: 10,
id: 123
}]
const orders = [{
shippinginfo: "",
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [{
id: 123,
qty: 5
}]
}
}];
let obj = {};
products.forEach((product) => {
obj[product.id] = product;
});
orders.forEach((order) => {
order.orderinfo.products.forEach((product) => {
product.price = obj[product.id].price * product.qty;
});
});
console.log(orders);
You can Do it Like This:
const products = [
{price: 10, id: 123}
]
const orders = [
{
shippinginfo: "",
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [
{
id: 123,
qty: 5
}
]
}
}
]
var sum = 0
for (let i = 0;i<orders.length;i++){
var order = orders[i]
var orderinfo = order["orderinfo"]
var products1 = orderinfo["products"]
for (let j = 0;j<products1.length;j++){
var product1 = products1[j]
for (let k = 0;k<products.length;k++){
if (products[k]["id"] == product1["id"]){
sum += products[k]["price"]*product1["qty"]
}
}
}
}
console.log(sum); // 50
const orders = [{
orderinfo: {
note: 'a message for the seller',
paymentType: 'visa',
products: [{
id: 123,
qty: 5
},
{
id: 13,
qty: 2
}]
}
}]
const products = [{
price: 10,
id: 123
},
{
price: 100,
id: 13
},
]
// finds price of order's product and multiply by qty
let sumOfOrders = orders.orderinfo.products.reduce((acc, cur) => acc + (products.find(f => f.id === cur.id)).price * cur.qty)

Categories