28 November 2026

Modern JavaScript Object.groupBy and Set Methods for Beginners: Clean Data

  Asp.Net CS By Example       28 November 2026

For years, JavaScript developers reached for helper libraries or verbose reduce() loops just to group records by category or find overlapping items between two lists. Modern JavaScript (ES2024/ES2025+) includes built-in Object.groupBy() and native Set math methods—union(), intersection(), and difference()—directly in browsers and Node.js.

Built-in JavaScript data helpers

Object.groupBy(items, fn) (Group arrays) • setA.union(setB) (Combine unique items) • setA.intersection(setB) (Find overlap)

1. Group Student Records with Object.groupBy()

Pass an array and a callback that returns the group key for each item:

const submissions = [
  { student: 'Aarav', track: 'dotnet' },
  { student: 'Maya', track: 'python' },
  { student: 'Liam', track: 'dotnet' },
  { student: 'Zoe', track: 'python' }
];

const byTrack = Object.groupBy(submissions, (item) => item.track);

console.log(byTrack.dotnet);
// [{ student: 'Aarav', track: 'dotnet' }, { student: 'Liam', track: 'dotnet' }]

Note: Object.groupBy returns a null-prototype object, which avoids collisions with built-in property names like toString.

2. Compare Rosters with Set.prototype.union and intersection

Use native Set methods to combine rosters or find students enrolled in both workshops (each method also accepts arrays directly as arguments):

const pythonClub = new Set(['Aarav', 'Maya', 'Noah']);
const reactClub = new Set(['Maya', 'Liam', 'Noah']);

const allMembers = pythonClub.union(reactClub);
const bothClubs = pythonClub.intersection(reactClub);

console.log([...allMembers]); // ['Aarav', 'Maya', 'Noah', 'Liam']
console.log([...bothClubs]);  // ['Maya', 'Noah']

Practice

  1. Use Object.groupBy to split a list of student scores into 'pass' (score >= 60) and 'review' groups.
  2. Use pythonClub.difference(reactClub) to list students who are in Python Club but not React Club.
  3. Pass a plain JavaScript array directly into pythonClub.union(['Zoe', 'Aarav']) and verify duplicates are removed automatically.

Continue learning: JavaScript Lessons and Practice.

References: MDN JavaScript Reference.

logoblog

Thanks for reading Modern JavaScript Object.groupBy and Set Methods for Beginners: Clean Data

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.