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

109
Views
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 answers
Answer question

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 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!