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

138
Views
Cómo contar textos que son iguales en un valor

tengo esta cadena:

 item_type = 'a, a, b'

¿Cómo puedo contar los valores para obtener algo como esto?

 number_of_a = 2 number_of_b = 1

Intenté algo como a continuación, pero obtuve algo de JavaScript para el error de cadena de entrada "[objeto Objeto]"

 if(item_type != null) { item_type = item_type.split(","); item_type.forEach(function(x) { number_of_a[x] = (number_of_a[x] || 0) + 1; }); }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

reduce es tu amigo, como con cualquier operación de agrupación

 const item_type = 'a, a, b'; const result = item_type.split(", ").reduce ( (a,i) => { a[i] = (a[i] +1 || 1) return a; },{}) console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

Si solo nos interesan los alfabetos, mejoramos la respuesta de @Tamas Szoke.

 const str = 'a, a, b' const chars = {} for (let char of str) { if(char.toUpperCase() != char.toLowerCase()){ chars[char] = chars[char] + 1 || 1; } } console.log(chars)

about 4 years ago · Juan Pablo Isaza Report

0

Si solo pudiera haber a o b , puedes hacerlo de esa manera:

 const item_type = 'a, a, b' let number_of_a = 0 let number_of_b = 0 if (item_type != null) { item_type .split(',') .map(el => el.trim()) //remove whitespaces from each element .forEach(el => el === 'a' ? number_of_a++ : number_of_b++) } console.log(`a: ${number_of_a}`) console.log(`b: ${number_of_b}`)

De lo contrario, debe usar una matriz o un objeto:

 const item_type = 'a, a, b' const occurrences = {} if (item_type != null) { item_type .split(',') .map(el => el.trim()) //remove whitespaces from each element .forEach(el => { if (!occurrences[el]) { occurrences[el] = 1 } else { occurrences[el] += 1 } }) } for (const [key, value] of Object.entries(occurrences)) { console.log(`${key}: ${value}`) }

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!