Skip to content

Instantly share code, notes, and snippets.

@faazah
Created June 28, 2022 14:26
Show Gist options
  • Save faazah/af05a3103a13ab4661d9b0903b974849 to your computer and use it in GitHub Desktop.
Save faazah/af05a3103a13ab4661d9b0903b974849 to your computer and use it in GitHub Desktop.
/*
You have been given a list of products which is having property productName, quantity and description.
PROBLEM STATEMENTS:
1. you need to write a function say, getUniqueProductCount which should return count of each Product(as an object) present in the given list of Products considering Product Name as Key.
Sample Output for the given listOfProducts will be :
{
"TV": 2,
"AC": 2,
"FAN": 1
}
2. you need to write a function say, getUniquePrducts which should return an array of objects by grouping the products based on the productName and summing up the quantity for the same products present in the given list of Products considering Product Name as Key.
Sample Output for the given listOfProducts will be :
[{
productName: "TV",
quantity: 20,
description: "television"
},
{
productName: "AC",
quantity: 10,
description: "air conditioner"
},
{
productName: "FAN",
quantity: 10,
description: "Ceiling Fan"
}
]
*/
const listOfProducts = [{
productName: "TV",
quantity: 10,
description: "television"
},
{
productName: "AC",
quantity: 5,
description: "air conditioner"
},
{
productName: "TV",
quantity: 10,
description: "television"
},
{
productName: "AC",
quantity: 5,
description: "air conditioner"
},
{
productName: "FAN",
quantity: 10,
description: "Ceiling Fan"
}
];
getUniqueProductCount();
function getUniqueProductCount() {
let uniqueProduct = {};
for (let i = 0; i < listOfProducts.length; i++) {
if (!uniqueProduct[listOfProducts[i].productName]) {
uniqueProduct[listOfProducts[i].productName] = 1;
} else uniqueProduct[listOfProducts[i].productName]++;
}
console.log(uniqueProduct);
}
getUniquePrducts()
function getUniquePrducts(){
let productTotalQuantity = [];
for (let i = 0; i < listOfProducts.length; i++) {
let flag = true;
for (let j = 0; j < productTotalQuantity.length; j++) {
if (listOfProducts[i].productName === productTotalQuantity[j].productName) {
productTotalQuantity[j].quantity =
productTotalQuantity[j].quantity + listOfProducts[i].quantity;
flag = false;
}
}
if (flag === true) {
productTotalQuantity.push(listOfProducts[i]);
}
}
console.log(productTotalQuantity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment