对现有数组按顾问分组统计,生成含顾问ID的重构数组
Solution to Group Customers by Consultant
Got it, let's solve this grouping problem! You want to take your flat array of customer-consultant pairs and restructure it into an array where each entry represents a consultant, includes their ID, and lists all their assigned customers. Here's a clean, efficient way to do this with JavaScript:
Step 1: Fix the Original Array (Add Valid Syntax)
First, let's correct the syntax of your input array (strings need quotation marks to be valid JavaScript):
const originalArray = [ {customer: 'bryan', id: 123, consultant: 'Dave', consultantID: 400}, {customer: 'sharon', id: 124, consultant: 'Dave', consultantID: 400}, {customer: 'bobby', id: 125, consultant: 'Simon', consultantID: 401}, {customer: 'chris', id: 126, consultant: 'Dave', consultantID: 400}, {customer: 'sanji', id: 127, consultant: 'Lars', consultantID: 402} ];
Step 2: Use reduce() to Group the Data
We'll use Array.reduce() to build our grouped structure incrementally, then convert it to the final array with Object.values():
const groupedByConsultant = Object.values( originalArray.reduce((acc, entry) => { // Check if we already have a group for this consultant if (!acc[entry.consultant]) { acc[entry.consultant] = { consultant: entry.consultant, consultantID: entry.consultantID, customers: [] }; } // Add the current customer to the consultant's list acc[entry.consultant].customers.push({ customer: entry.customer, id: entry.id }); return acc; }, {}) );
Step 3: Resulting Structure
The groupedByConsultant variable will now match your desired structure:
[ { consultant: 'Dave', consultantID: 400, customers: [ {customer: 'bryan', id: 123}, {customer: 'sharon', id: 124}, {customer: 'chris', id: 126} ] }, { consultant: 'Simon', consultantID: 401, customers: [{customer: 'bobby', id: 125}] }, { consultant: 'Lars', consultantID: 402, customers: [{customer: 'sanji', id: 127}] } ]
Quick Breakdown
reduce(): This method is perfect here because it lets us build up our grouped object one entry at a time.- Group Initialization: If a consultant isn't already in our accumulator object, we create a new group with their name, ID, and an empty list for customers.
- Populate Customers: For every entry in the original array, we push the customer's details into the matching consultant's customer list.
Object.values(): Converts our intermediate grouped object (with consultant names as keys) into a clean array of consultant objects—exactly the structure you need.
内容的提问来源于stack exchange,提问作者Sorvah
相关产品推荐
相关产品推荐

