How to Count Unique Value from Object of Array in JavaScript

How to count unique value from object of array in javascript

You can loop through array using "for..of" and create a temporary object to save data in every loop. If same id exists in tempObject then increment count by 1

var arr = [  { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }  , { CategoryId: "9872cce5af92", CategoryName: "Category 2", CategoryColor: "purple" }  , { CategoryId: "b5c3f43f941c", CategoryName: "Category 1", CategoryColor: "cgreen" }]
var tempResult = {}
for(let { CategoryColor, CategoryId } of arr) tempResult[CategoryId] = { CategoryId, CategoryColor, count: tempResult[CategoryId] ? tempResult[CategoryId].count + 1 : 1 }
let result = Object.values(tempResult)
console.log(result)

Javascript count unique values of object property in an object array

You could reduce the list into a Set and then grab the size.

const organisations = [
{ "id": 1, "name": "nameOne" },
{ "id": 2, "name": "nameTwo" },
{ "id": 3, "name": "nameOne" }
];

const uniqueItems = (list, keyFn) => list.reduce((resultSet, item) =>
resultSet.add(typeof keyFn === 'string' ? item[keyFn] : keyFn(item)),
new Set).size;

console.log(uniqueItems(organisations, 'name'));
console.log(uniqueItems(organisations, ({ name }) => name));

How do I count the number of unique elements in an array of objects by an object property?

Something like this might work:

function countTableId(orders){
// sets are, well, sets of unique items. no duplicates allowed
let uniqueId = new Set();
for(let ord of orders){
uniqueId.add(ord.table_id);
}
// the size of the set is the number of unique items we added
return uniqueId.size;
}

You could do the same with the food_id property in another function.

@Felix King has a one-line way of doing this, so props to him. It uses the set object and Array.prototype.map()

let unique_table_id_count = new Set(orders.map(x => x.table_id)).size
let unique_food_id_count = new Set(orders.map(x => x.food_id)).size

.map() will loop through the array and look at each table_id, then it will try to add that to the set. The set object will discard an element if it already exists, so we only get unique values. Finally, because of chaining, we can just get the size of the set and we're done!

Count unique elements in array without sorting

A quick way to do this is to copy the unique elements into an Object.

var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}

When this loop is complete the counts object will have the count of each distinct element of the array.

How to count all unique values in an array of objects?

You can use a Map to collect the dates that go with a name (check your spelling in the example data!), and then you can iterate those map entries to both get the dates-array length, and unique count (via Set):

const arr = [{name: "Edward",date: "24 March"},{name: "Banana",date: "12 March"},{name: "Edward",date: "23 March"},{name: "Edward",date: "23 March"}];

let map = new Map(arr.map(o => [o.name, []]));
for (let {name, date} of arr) map.get(name).push(date);
let result = Array.from(map.entries(), ([name, dates]) =>
({name, uniqueDate: new Set(dates).size, totalSubmit: dates.length})
);
console.log(result);

JavaScript: Get unique values and their counts from an array of objects?

you could use map for this purpose as:

var distances = {};
$.map(electrons,function(e,i) {
distances[e.distance] = (distances[e.distance] || 0) + 1;
});

or

var distances = {};
$.each(electrons,function(i,e) {
distances[this.distance] = (distances[this.distance] || 0) + 1;
});

Also may I point out to you that although this code good to look and compact, this is not generally faster. Better make your code more faster and more easy to look at as:

var distances = {},e;
for (var i = 0,l=electrons.length; i < l; i++) {
e = electrons[i];
distances[e.distance] = (distances[e.distance] || 0) + 1;
}

How to count number of occurrences of distinct values from an array of objects in Javascript?

You'll need to know to which name a count belongs, so I propose not to output an array that gives you no clue about that, but an object keyed by names and with as value the corresponding count:

var result = array.reduce( (acc, o) => (acc[o.name] = (acc[o.name] || 0)+1, acc), {} );

var array =    [        {"name":"abc","age":20},        {"name":"abc","age":20},        {"name":"abc","age":20},        {"name":"xyz","age":21},        {"name":"xyz","age":21}    ];    var result = array.reduce( (acc, o) => (acc[o.name] = (acc[o.name] || 0)+1, acc), {} );
console.log(result);

How to get distinct values from an array of objects in JavaScript?

If this were PHP I'd build an array with the keys and take array_keys at the end, but JS has no such luxury. Instead, try this:

var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
if( flags[array[i].age]) continue;
flags[array[i].age] = true;
output.push(array[i].age);
}

Javascript / ES6 find unique elements and count them in array

You could use Map and store the reference to the new inserted objects of the result array.