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

238
Views
¿Hay alguna manera de crear rangos dinámicos dada una matriz de valores y contar cuántos pertenecen a cada rango?

Así que tengo una interfaz con un Piechart y quiero mostrar el porcentaje de edades en mis clientes (una tabla de base de datos). He almacenado la edad de cada cliente, así que tengo una matriz como esta.

ingrese la descripción de la imagen aquí

 const ages = [12,42,23,42,12,65,75,12,43,54,12,53,24,23,54,64,76,12,42];

Dados estos valores, quiero terminar teniendo algo como esto

 const data = { labels: ['12-20', '21-40', '41-60', '61-76'] dataSet: [4, 6, 2, 5] // This is the amount of ages between each range. The sum of these must be equivalent of the length of the array }

Esto es lo que he probado hasta ahora

 const ages = [12, 42, 53, 12, 32, 12, 52, 66, 76, 87, 23, 12, 43, 12, 43, 54, 65].sort((a, b) => a - b); const minAge = Math.min(...ages); const maxAge = Math.max(...ages); const q1 = ages[Math.floor(ages.length / 4)]; const q2 = ages[Math.floor(ages.length / 2)]; const q3 = ages[Math.floor(ages.length * 3 / 4)]; let firstRangeCount = 0; let secondRangeCount = 0; let thirdRangeCount = 0; let fourthRangeCount = 0; for (const age of ages) { if (age) { if (age <= q1) { firstRangeCount++; } else if (age <= q2) { secondRangeCount++; } else if (age <= q3) { thirdRangeCount++; } else { fourthRangeCount++; } } } const data = { labels: [ `${minAge} - ${q1}`, `${q1} - ${q2}`, `${q2} - ${q3}`, `${q3} - ${maxAge}`, ], datasets: { label: 'Ages', data: [firstRangeCount, secondRangeCount, thirdRangeCount, fourthRangeCount], } }

Pero el problema con esta solución es que no es dinámica. Si la matriz de edades contiene menos datos, 4 rangos no serían apropiados.

¿Cómo puedo hacer que estos rangos sean "dinámicos"? He leído algo sobre el rango intercuartílico pero no me ayudó mucho

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Pruebe esto (se agregaron comentarios descriptivos en el siguiente fragmento de código) :

 // Input array const ages = [12,42,23,42,12,65,75,12,43,54,12,53,24,23,54,64,76,12,42]; // data object with range array const data = { labels: ['12-20', '21-40', '41-60', '61-76'], dataSet: [] } // declare a variable which will contain the count of occurance based on the range const obj = {}; // logic to find out the counts and pushed into an range array in an object. data.labels.forEach(label => { const splittedLabel = label.split('-') const filteredAges = ages.filter(e => e >= splittedLabel[0] && e <= splittedLabel[1]); obj[label] = []; obj[label].push(...filteredAges); }); // getting the length const dataSet = Object.values(obj).map(arr => arr.length); data.dataSet = dataSet; // Result console.log(data);

about 4 years ago · Santiago Gelvez 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!