简体   繁体   中英

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: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

I want to count the number of unique entries in each key.

For example,

  • For the key category there are 2 unique entries.

  • For the key name there are 5 unique entries.

I tried using Object.keys(products).length , but that only gives the total number of rows in the array.

How can I get the counts?

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 = new Set(products.map(p => p.category)).size;

You can achieve this by following

var map = {};

products.map(function(product){
    map[product.category] = undefined;        
});

console.log(Object.keys(map).length);

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM