JavaScript: Group by groupName and Count Unique Names in an Array of Objects
This JavaScript code snippet demonstrates how to group an array of objects by 'groupName' and count the number of unique 'name' values within each group.
let arr = [
{
name: 'm1',
groupName: 'group1',
type: 'Messense_Mutation'
},
{
name: 'm1',
groupName: 'group2',
type: 'Messense_Mutation'
},
{
name: 'm1',
groupName: 'group3',
type: 'Messense_Mutation'
},
{
name: 'm1',
groupName: 'group7',
type: 'Messense_Mutation',
showValue: '414141',
value: 0.21,
},
{
name: 'm1',
groupName: 'group4',
type: 'Multi_Hit',
showValue: '313131',
value: 0.03,
},
{
name: 'm2',
groupName: 'group1',
type: 'Frame_Shit_del',
showValue: '444',
value: 0.89,
},
{
name: 'm2',
groupName: 'group2',
type: 'Splite_Site',
showValue: '555',
value: 0.42,
},
{
name: 'm2',
groupName: 'group3',
type: 'Nonsense_Mutation',
showValue: '666',
value: 0.78,
},
{
name: 'm2',
groupName: 'group4',
type: 'Frame_Shit_del',
showValue: '777',
value: 0.23,
},
{
name: 'm5',
groupName: 'group4',
type: 'Splite_Site',
showValue: '888',
value: 0.56,
}
]
const groupByName = {};
arr.forEach(obj => {
if (groupByName[obj.groupName]) {
groupByName[obj.groupName].push(obj.name);
} else {
groupByName[obj.groupName] = [obj.name];
}
});
for (let groupName in groupByName) {
const names = groupByName[groupName];
const uniqueNames = [...new Set(names)];
console.log(`Group ${groupName} has ${uniqueNames.length} names: ${uniqueNames.join(', ')}`);
}
// Output:
// Group group1 has 2 names: m1, m2
// Group group2 has 2 names: m1, m2
// Group group3 has 2 names: m1, m2
// Group group7 has 1 names: m1
// Group group4 has 3 names: m1, m2, m5
Explanation:
- Grouping: The code uses a
forEachloop to iterate through thearrarray. For each objectobj, it checks if thegroupNameexists as a key in thegroupByNameobject. If it does, it adds theobj.nameto the existing array for thatgroupName. Otherwise, it creates a new array withobj.nameas the first element. - Counting Unique Names: After grouping, the code loops through the
groupByNameobject. For eachgroupName, it uses theSetobject to get the uniquenamesand then counts the length of the resulting array to get the number of unique names. - Output: The code outputs the results in the format
Group groupName has count names: name1, name2, ....
Key Concepts:
- Array Iteration: Using
forEachto iterate through an array of objects. - Object Properties: Accessing and manipulating object properties using dot notation (e.g.,
obj.groupName). - Sets: Utilizing
Setto find unique elements in an array. - Template Literals: Using backticks (`) to create formatted strings with embedded variables.
This code snippet effectively groups objects by a common property (groupName) and provides a clear and concise way to count the unique values of another property (name) within each group. It's a useful technique for data analysis and organization in JavaScript.
原文地址: https://www.cveoy.top/t/topic/mj55 著作权归作者所有。请勿转载和采集!