• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

167
Views
How do I count the number of unique elements in an array of objects using the object property?

I have an array that looks like this:

let arr = [
    {'option1':1},{'option1':1},{'option1':1},
    {'option1':2},{'option1':2},
    {'option1':3},
    {'option2':1},{'option2':1}
]

I need to iterate through the array and count the occurrences of each element with the same property to be displayed like this:

   option1:{
            1:3,
            2:2,
            3:1,
           },
   option2:{
            1:2,
           }

Basically saying that option1 with a property of 1 has 3 counts, option1 with a property of 2 has 2 counts, option1 with a property of 3 has 1 count and so on.

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

this way...

let arr = 
  [ { option1: 1 }, { option1: 1 }, { option1: 1 } 
  , { option1: 2 }, { option1: 2 } 
  , { option1: 3 } 
  , { option2: 1 }, { option2: 1 } 
  ] 

let obj = arr.reduce((r,o)=>
  {
  let [name,num] = Object.entries(o)[0] 
  if (!r[name]) r[name] = {}
  if (!r[name][num]) r[name][num] = 1
  else               r[name][num]++
  return r
  },{})

console.log( obj )
.as-console-wrapper { max-height: 100% !important; top: 0 }

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error