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

115
Views
Can I have an object key as part of an array?

I am trying to sort some numbers, and I want to count the number of times that an array has a certain number.

My question is more about the structure of an the array than the counting the number part. I would like to build an array that looks like this below.

let numbers = [1,2,3,4,4,4,5,5,6];

How could I make the data structure below?

numbers[3].count // this will be equal to 3 after I loop through;

How do I make each part of the array have an object parameter?

Do I just loop through like so?

for (let i = 0; i < numbers.length; i++){
  numbers[i] = {
    count: 0
  }
}

I understand this wont give me the right count, but I don't care about that part of the problem. I would like to solve that on my own. I just need to be sure that this is the correct way to add the object parameters.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I would build these functions on my own. Something like this You can copy and paste this in the console of your browser.

// my numbers list
const numbers = [1, 2, 3, 4, 4, 4, 5, 5, 6];
// reduced to unique entries
const uniques = [...new Set(numbers)];
// function to count occurrences in my list of number
const count = (n) => numbers.filter((num) => num === n).length;
// you can test here
console.log(`counting ${uniques[4]}s`, count(uniques[4]));
// get these as object
console.log(uniques.map((unique) => ({[unique]: count(unique)})))
about 4 years ago · Juan Pablo Isaza Report

0

Simplest way to achieve this by using Array.forEach().

let numbers = [1,2,3,4,4,4,5,5,6];

const obj = {};

numbers.forEach((item) => {
    obj[item] = (obj[item] || 0) + 1;
});

console.log(obj);

about 4 years ago · Juan Pablo Isaza Report

0

const numbers = [1,2,3,4,4,4,5,5,6];
 
const counts = {};

numbers.forEach((x) => counts[x] = (counts[x] || 0) + 1);

console.log(counts)
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!