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

110
Visualizações
Javascript reduce method for object

Now I'm learning about reduce of Javascript. In below code, I don't understand acc[key] because we can access to properties of objects by using acc["key"] or acc.key . That's what I learned. but obviously the code below works correctly..why?

const arr = ['Cat', 'Dog', 'Bird', 'Cat']
const result = arr.reduce((acc, key) => {
    if (key in acc) {
        acc[key]++
    } else {
        acc[key] = 1
    }
    return acc
}, {})

console.log(result)
// { Cat: 2, Dog: 1, Bird: 1 }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So as @Alexandro mentioned that key is a string, indeed it is the value or values of the array arr which their type is string. Moreover We know that to access values of an object we follow two ways either square notation (e.g. arr[key]) or dot notation (e.g. arr.key). We perfer to use square notation in case there is a key made or contains space or other special chars.

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