How To Count Number Of Objects In An Array Per Key?
I have a JavaScript array which has the following contents: var products = [ {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sportin
Solution 1:
You can reduce array to get unique values as keys of reduced object and then apply Object.keys()
, for example:
var categoryCount = Object.keys(products.reduce(function(r, o) {
r[o.category] = 1;
return r;
}, {})).length;
In ECMAScript 2015 you can use Set data structure to get unique values:
const categoryCount = newSet(products.map(p => p.category)).size;
Solution 2:
You can achieve this by following
var map = {};
products.map(function(product){
map[product.category] = undefined;
});
console.log(Object.keys(map).length);
Solution 3:
I was able to achieve the same through a one line code. I am unsure if this is the most efficient one though:
var categoryCount = $.unique(products.map(function (d) {return (d.category);}));
alert(categoryCount.length)
Post a Comment for "How To Count Number Of Objects In An Array Per Key?"