Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
How to count texts that are the same in a value

I have this string:

item_type = 'a, a, b'

How can I count the values so I would get something like this:

number_of_a = 2
number_of_b = 1

I tried something like below but got some JavaScript for input string "[object Object]" error

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 Respostas
Responde à pergunta

0

reduce is your friend, as with any grouping operation

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 Relatório

0

If we are interested in only alphabets, improving the @Tamas Szoke answer.

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 Relatório

0

If there could be only a or b you can do it that way:

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}`)

Otherwise you should use an array or an object:

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda