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

119
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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