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:
- If product 1, output
you have 2 One Plus - If product 2, output
you have 1 One Plus and 1 Apple
Below 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?
Sebastian Simon
19.8k8 gold badges61 silver badges88 bronze badges
asked Jun 2, 2020 at 17:53
user3872094
3,3739 gold badges39 silver badges80 bronze badges
5 Answers 5
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));
answered Jun 2, 2020 at 18:08
gyohza
8561 gold badge8 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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));
Comments
const product1s = product1.reduce((acc, product) => {
acc[product.Brand] = (acc[product.Brand] || 0) + 1;
return acc;
}, {});
console.log(
`You have ${
Object.keys(product1s).map(product => `${product1s[product]} ${product}`).join(" and ")
}`
);
Sebastian Simon
19.8k8 gold badges61 silver badges88 bronze badges
6 Comments
Ibraheem
@gyohza indeed! Beat me to it! But check your return value in your reduction?
gyohza
You mean this bit
(acc[val.Brand] || 0) + 1? Yep, it's actually the exact same expression. :Pgyohza
Actually it's a quite standard answer, so it's no wonder both are so alike.
Ibraheem
@gyohza I meant returning acc after the comma, a neat JS shorthand I’ve forgotten about! Thanks!
gyohza
Oh! Yeah. That is different between our codes, it seems. The comma operator was just syntactic sugar though - it's easier on the eyes not to have to create a new block for the function body.
|
You first have to count the occurances, than its just a matter of string concat or templates
function strinify(a) {
let occurances = {};
a.forEach(function(e,i){
if( e.Brand in occurances ) {
occurances[e.Brand] ++;
} else {
occurances[e.Brand] = 1;
}
});
let str = [];
for( brand in occurances ){
count = occurances[brand];
str.push(count + " " + brand);
};
return "you have " + str.join(" and ");
}
console.log(strinify([
{
"Brand": "One Plus"
},
{
"Brand": "One Plus"
},
{
"Brand": "Apple"
}
]));
Comments
const order1 = [
{
"Brand": "One Plus",
"test" : "test"
},
{
"Brand": "One Plus"
},
{
"Bar": "Foo"
}
];
const order2 = [
{
"Brand": "One Plus"
},
{
"Brand": "Apple"
}
];
const orderToString = (order) => {
if(order == null) return;
const productsWithBrand = order.filter(product => Object.keys(product).includes('Brand'));
const productBrandCounter = (counter, product) => (counter[product.Brand] = (counter[product.Brand] || 0) + 1, counter);
const countPerProduct = productsWithBrand.reduce(productBrandCounter, {});
const stringPerProduct = Object.keys(countPerProduct).map(brand => `${countPerProduct[brand]} ${brand}`);
return `You have ${stringPerProduct.join(' and ')}`;
}
console.log(orderToString(order1));
answered Jun 2, 2020 at 21:01
Jens Ingels
8161 gold badge9 silver badges14 bronze badges
Comments
lang-js
JSON.stringify(obj)as key instead of just usingobj.Brandstringisn't the keyword here.JSONat all. Just group and count: Group array of objects by value and get count of the groups, then reduce the keys and counts.