Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda