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

168
Visualizações
incrementing a set if existing

I have a string "abacabad" being passed in to my function as s

What I want to do:

  • create a new set
  • go through each letter from the string. if the letter exists I increment it by 1
  • if it doesn't exist we create the set by initializing it as 1

What my code is logging:

Set(0) { a: 1, b: 1, c: 1, d: 1 }

what it should be logging:

Set(0) { a: 4, b: 2, c: 1, d: 1 }


function solution(s) {
  arr = new Set()
  for (e of s) {
    if (e in arr) {
      arr[e]++;
    }
    if (arr.has(e) == false) {
      arr[e] = 1;
    }
  }
  console.log(arr)
}

solution('abacabad');

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A Set is a collection of unique elements. It's not a Map (key/value) store.

There's tons of issues in that code so I won't enumerate them all, but you simply aren't using the right kind of object and then are mixing APIs, notably defining keys of objects mixed with the actual Set's API.

function solution(s) {
  const countByChar = new Map();
  for (char of s) {
    const count = countByChar.get(char) || 0;
    countByChar.set(char, count + 1);
  }
  return countByChar;
}

const countByChar = solution('abacabad');

console.log(Array.from(countByChar.entries()));

about 4 years ago · Juan Pablo Isaza Relatório

0

You're conflating two different data structures:

  • Sets, which are collections of values only (eg ('a, 'b', 'c', 'd'), and
  • Objects, which are collections of key-value pairs (eg { a: 1, b: 2 })

Set methods include .has and .add. But Sets are also objects, so you can use standard object property assignment on them as well - but you shouldn't. If you want a Set, use Set methods (and Set methods only) for collecting data on it. Here, you're putting a property directly onto the Set object (with arr[e] =), but you're using the Set method .has, which checks something completely different. .add and has looks at values in the Set's internal data structure (not visible by any mechanism other than other Set methods), and you're never using .add, so your Set never gets any values put into it.

A Set won't work well here anyway, because you want a collection of key-value pairs, not just a collection of values. Use a standard object instead, or a Map.

function solution(s) {
  const obj = {};
  for (const char of s) {
    obj[char] ??= 0;
    obj[char]++;
  }
  console.log(obj);
}

solution('abacabad');

If you wanted a Map:

function solution(s) {
  const map = new Map();
  for (const char of s) {
    map.set(
      char,
      (map.get(char) || 0) + 1
    );
  }
  console.log([...map.entries()]);
}

solution('abacabad');

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