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

219
Vistas
Appending new keys, and changing values in for/if loop

My current goal is to take items in array integers and create a key pair value based on how many times the key appeared in integers. My logic is: for i in integers, if i is in integers 2 already, increment that key's value by 1. if it doesn't exist, create the key and pair it with a value of 1. It's been a few hours now and after heavy googling I can't seem to find where im messing my logic up.

//require realdine-sync module
var readlineSync = require('readline-sync');
//initialize variable and list
var integer;
integers2 = {};
var integers = [];
//user input
integer = readlineSync.question('Integer?: ')
//check user input and append any integer besides 0
while (integer != 0 && integer >= 1 && integer <= 100){
console.log("not 0!")
integers.push(integer)
integer = readlineSync.question('Integer?: ')
}
console.log(integers);
for(i in integers){if (i in integers2){integers2[i] += 1}else{integers2[i] = 1}
   
}
console.log(integers2)
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

let integers2 = {}

integers = [5, 4, 5, 2, 4, 7, 5];

// you were using 'in' instead 'of', 'in': gives you index , 'of'?: gives you value of array
for (let i of integers) {
    if (integers2[i]) { // if key exist increment value by one
        integers2[i] += 1
    } else { // else add 1 as the first value
        integers2[i] = 1
    }
}
console.log(integers2);

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is a solution that you can try which works. It uses the same logic as you described in the question. This solution uses Array.prototype.reduce() with a Map().

const howMany = arr => arr
  .reduce(
    (map, n) => map.set(n, (map.get(n) ?? 0) + 1), 
    new Map()
  )

console.log([...howMany([3, 4, 6, 4, 5, 5, 5])])

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