Count duplicate value from array into array of object in javascript
First count the character number of occurrence in uniqueCount
array. Then make the resulting array of object using map
as below
var uniqueCount = ['a','a','b','c','d','a','a'];var duplicateCount = {};uniqueCount.forEach(e => duplicateCount[e] = duplicateCount[e] ? duplicateCount[e] + 1 : 1);var result = Object.keys(duplicateCount).map(e => {return {key:e, count:duplicateCount[e]}});console.log(result);
How to get count of duplicate objects in Array
You can easily achieve this using reduce and map. First, count all the occurrences of all objects and then add the property dynamically.
const arr = [
{
partNum: "ACDC1007",
brandName: "Electric",
supplierName: "Electric",
},
{
partNum: "ACDC1007",
brandName: "Electric",
supplierName: "Electric",
},
{
partNum: "ACDC1007",
brandName: "Electric",
supplierName: "Electric",
},
{
partNum: "ACDC1009",
brandName: "Electric",
supplierName: "Electric",
},
{
partNum: "ACDC1000",
brandName: "Electric",
supplierName: "Electric",
},
];
const countDict = arr.reduce((acc, curr) => {
const { partNum } = curr;
if (acc[partNum]) ++acc[partNum];
else acc[partNum] = 1;
return acc;
}, {});
const result = arr.map((obj) => {
obj["count"] = countDict[obj.partNum];
return obj;
});
console.log(result);
Count duplicates in an array of objects and sum up values located in the objects
You could collect with an object and get the values from it.
const
users = [{ name: 'John', gender: 'Male', orders: 20 }, { name: 'Doe', gender: 'Male', orders: 8 }, { name: 'Ada', gender: 'Female', orders: 10 }, { name: 'David', gender: 'Male', orders: 30 }],
result = Object.values(users.reduce((r, { gender, orders }) => {
r[gender] ??= { gender, count: 0, totalOrders: 0 };
r[gender].count++;
r[gender].totalOrders += orders;
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Count duplicate values in an array and return count with an additional value using Javascript
You could take categoryTitle
directly without mapping the array before.
function categoriesCount (things) { return things.reduce((hash, { categoryTitle }) => { hash[categoryTitle] = (hash[categoryTitle] || 0) + 1; return hash; }, {});}
const things = [{ id: 1, title: 'Something', categoryId: 1, categoryTitle: 'Category 1' }, { id: 2, title: 'Another thing', categoryId: 1, categoryTitle: 'Category 1' }, { id: 3, title: 'Yet another thing', categoryId: 2, categoryTitle: 'Category 2' }, { id: 4, title: 'One more thing', categoryId: 4, categoryTitle: 'Category 3' }, { id: 5, title: 'Last thing', categoryId: 4, categoryTitle: 'Category 3' }]
console.log(categoriesCount(things));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Javascript - Counting duplicates in object array and storing the count as a new object
I would stick to reduce
, use a Map
and spread its values
to get the final result:
const names = [{ _id: 1 }, { _id: 1}, { _id: 2}, { _id: 1}];
const result = [...names.reduce( (mp, o) => {
if (!mp.has(o._id)) mp.set(o._id, { ...o, count: 0 });
mp.get(o._id).count++;
return mp;
}, new Map).values()];
console.log(result);
javascript counting duplicates in array
I guess the main confusion comes from this line:
counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
The ||
operator returns what is on the left side if it is "truthy" (anything other than the "falsy" values false
, 0
, ''
, null
, undefined
, and NaN
), otherwise it returns what is on the right hand side.
If ResultArray[p]
is not inside of counts
, then counts[ResultArray[p]]
will be undefined
. Since undefined + 1
is NaN
, the left hand side of ||
is "falsy", so it will return the right hand side 1
.
Otherwise, counts[ResultArray[p]]
will be the amount of times we've already seen ResultArray[p]
, and we'll add 1
to it. In this case the left hand side will be "truthy" and it will return the new count.
Related Topics
How to Pass Checkbox State to Onclick Function in React
How to Call a Function When Element Is Loaded At Angular
How to Convert Seconds to Minutes and Hours in JavaScript
How to Get a File() or Blob() from an Url in JavaScript
Javascript Loop Wait Until API Call Finished
How to Append My Data in Nested Object
Remove Specific Characters from String Jquery
How to Get List of All Timezones in JavaScript
Typeerror: Cannot Create Property '_Id' on String
Sequelize - How to Return Json Objects of the Database Results Only
How to Remove a Parameter from a Url
What Is the Opposite of Evt.Preventdefault();
Uncaught Referenceerror: (Function) Is Not Defined At
Is It Okay to Call Onclick on an Anchor Tag in Reactjs
Adding Script Tag to React/Jsx
How to Access a Model Attribute With JavaScript Variable