I have two arrays as below:
var product1 = [
{
"Brand": "One Plus"
},
{
"Brand": "One Plus"
}
];
var product2 = [
{
"Brand": "One Plus"
},
{
"Brand": "Apple"
}
];
I want to loop through the array and print the following:
you have 2 One Plusyou have 1 One Plus and 1 AppleBelow is the code that I tried.
var product1 = [
{
"Brand": "One Plus"
},
{
"Brand": "One Plus"
}
];
var product2 = [
{
"Brand": "One Plus"
},
{
"Brand": "Apple"
}
];
counter1 = {}
product1.forEach(function(obj) {
var key = JSON.stringify(obj)
counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
var key = JSON.stringify(obj)
counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);
I’m able to get the JSON output, but how can I get it in the sentence format?
How about this?
var product1 = [{
"Brand": "One Plus"
},
{
"Brand": "One Plus"
}
];
var product2 = [{
"Brand": "One Plus"
},
{
"Brand": "Apple"
}
];
function countProducts(arr) {
let counter = arr.reduce((acc, val) =>
(acc[val.Brand] = (acc[val.Brand] || 0) + 1, acc), {});
let strings = Object.keys(counter).map(k => `${counter[k]} ${k}`);
return `You have ${strings.join(' and ')}`;
}
console.log(countProducts(product1));
console.log(countProducts(product2));
const product1 = [
{Brand: "One Plus"},
{Brand: "One Plus"},
];
const product2 = [
{Brand: "One Plus"},
{Brand: "Apple"},
];
function whatYouHaveIn(list) {
return `You have ` + Object.entries(list.reduce((a, c) => {
a[c.Brand] = a[c.Brand] || 0;
a[c.Brand]++;
return a;
}, {})).map(([brand, count]) => `${count} ${brand}`).join(` and `);
}
console.log(whatYouHaveIn(product1));
console.log(whatYouHaveIn(product2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With