1

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?

1
  • I can't think of any one-liner, but using just forEach should work Commented Mar 24, 2016 at 17:28

3 Answers 3

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 = new Set(products.map(p => p.category)).size;
Sign up to request clarification or add additional context in comments.

Comments

0

You can achieve this by following

var map = {};

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

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.