I want to calculate number of unique value and put that in new array. I have below array:
[
{ CategoryId: \"b5c3f43f941c\", CategoryName: \"Category 1\", Categ
You can sort the array first then count the duplicates. The downside is it will modify the original yourArray
due to being sorted, so use with caution.
yourArray.sort((a, b) => {
if (a.CategoryName > b.CategoryName) {
return 1;
}
if (a.CategoryName < b.CategoryName) {
return -1;
}
return 0;
});
var pivot = yourArray[0];
pivot.count = 0;
var counted = [pivot];
yourArray.forEach(item => {
if (item.CategoryId === pivot.CategoryId) {
pivot.count++;
} else {
pivot = item;
pivot.count = 1;
counted.push(pivot);
}
});