Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
¿Cómo crear un contador usando recursividad para obtener el total de empleados (directos o indirectos) bajo un manager_id en javascript?

Tengo un archivo de Excel con datos como este

Nombre ID del trabajador ID de administrador
Tomás 179 180
liz 150 179
Ricky 120 179
sona 113 150
Preet 558 150
Mina 89 558
Yukti 45 120

Y quiero una función CountEmployee (manager_id) que devolverá todos los empleados debajo de él. Por ejemplo:

ContarEmpleados(179) = 6 , ContarEmpleados(150) = 3

Estoy usando la biblioteca papa parse para analizar este Excel en un objeto y escribí una función recursiva para obtener el empleado total.

parseCsv para analizar el csv

 function parseCsv() { return new Promise((resolve, reject) => { Papa.parse("Employees.csv", { download: true, complete: function (results) { return resolve(results); }, }); }); }

CountDirectEmployees para obtener la identificación de empleados directos de un administrador

 async function CountDirectEmployee(data) { var countDirect1 = 0 const results = await parseCsv(); results.data.map((row, index) => { if (row[2] == data) { countDirect1 = countDirect1 + 1 } }) return countDirect1; }

Y finalmente,

CountEmployee debe devolver el recuento final

 async function CountEmployee(data,count) { const results = await parseCsv(); CountDirectEmployee(data).then( function(count1){ results.data.forEach((row, index) => { if (row.ManagerId == data) { count1 = count+count1 CountEmployee(row[1],count1) } }) } ) return count }

Sé que mi lógica es incorrecta para la función CountEmployee, en alguna parte. No se puede resolver el problema.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Cambiar ligeramente el código nos permitirá llamar a CountEmployee de forma recursiva. Pasaríamos la variable de filas para cada llamada (para ahorrar lectura repetidamente), luego agregaríamos el recuento de trabajadores directos de cada empleado para obtener el total de cada gerente.

La función getDirectEmployees() usa un Array.filter() simple para devolver los empleados que trabajan directamente para cada gerente.

 const employees = [ [ 'Tom', 179, 180 ], [ 'Liz', 150, 179 ], [ 'Ricki', 120, 179 ], [ 'Sona', 113, 150 ], [ 'Preet', 558, 150 ], [ 'Mina', 89, 558 ], [ 'Yukti', 45, 120 ] ]; // Simulate what papa parse returns... function parseCSV() { return Promise.resolve(employees); } function displayRow(...row) { console.log(...row.map(f => (f + '').padEnd(15))) } async function testCounts() { console.log('Direct and total counts for each worker:\n'); let rows = await parseCSV(); displayRow('Name', 'Id', 'Direct', 'Total') for(let [name, workerId, managerId] of rows) { let directEmployees = CountDirectEmployees(workerId, rows); let totalEmployees = CountEmployee(workerId, rows); displayRow(name, workerId, directEmployees, totalEmployees) } } function getDirectEmployees(id, rows) { return rows.filter(([name, workerId, managerId]) => managerId === id); } function CountDirectEmployees(managerId, rows) { return getDirectEmployees(managerId, rows).length; } function CountEmployee(managerId, rows) { // Count direct employees, then count employees of each of these let directEmployees = getDirectEmployees(managerId, rows); let count = directEmployees.length; for(let [name, workerId] of directEmployees) { count += CountEmployee(workerId, rows); } return count; } testCounts()
 .as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!